Compare commits

..
230 Commits
Author SHA1 Message Date
hausgeist b34ef206f8 cc: gate on DB readiness + real healthchecks (start.sh has no set -e and wait-for-it passes mid-initdb)
- database: pg_isready healthcheck; calcom depends_on service_healthy
- calcom: healthcheck probes /auth/login with redirects (upstream wget --spider / fails on 307)
2026-09-28 08:16:12 -07:00
hausgeist 1c3c661726 cc: fix DB wiring — base compose hardcodes unicorn_user/magical_password and builds DATABASE_URL from raw creds (Prisma URL-parse crash with base64 pw)
- docker-compose.cc.yml: database env + calcom DATABASE_URL/DIRECT_URL from .env
- cc.env.example: require HEX (URL-safe) secrets; hex generation commands
2026-09-28 06:44:44 -07:00
hausgeist 3dbad3113d cc: build-based deploy — cal.diy publishes no prebuilt release images
Verified: Docker Hub calcom/cal.diy has 0 tags; scarf/ghcr mirrors serve none.
The upstream Dockerfile + compose build args are the deploy path.
2026-09-28 00:23:53 -07:00
hausgeist b1173fc8c3 cc: CC deployment source-of-truth pinned at v6.2.0 (issue #11)
- docker-compose.cc.yml: pin calcom v6.2.0 + postgres 16-alpine + redis 7-alpine;
  studio + calcom-api off (reserved profiles)
- cc.env.example: CC production env spec (webapp URL, telemetry off, branding)
- cc/README.md: mirror manifest + upstream-merge process
2026-09-27 23:36:33 -07:00
khushal-winnerandSahitya Chandra 1c193cca86 docs: document Windows setup fix for prisma .env symlink error (#28101)
Post release / release (push) Canceled after 0s
Release Docker / Prepare Release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
* docs: add Windows fix for prisma .env symlink issue

* Remove 'link-as-an-app' from redirect apps list

Removed 'link-as-an-app' from the list of apps.

* Update README.md

removed option 2

* Update README.md

* Update README.md

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-03-01 12:42:42 +00:00
17af50bbdc feat: add per-host locations seed data in Acme Org for QA (#27832)
* fix: host location option

* feat: add per-host locations seed data for Round Robin event type

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: move per-host locations seed to Acme Org with dedicated event type

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: check app existence before creating credentials in per-host location seed

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: remove credential-based app seeding, use simple location types instead

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Udit Takkar <udit222001@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2026-02-26 18:51:11 +00:00
5242e419d9 feat: Calendar Sync (#24124)
* feat: calendar cache and sync - wip

* Add env.example

* refactor on CalendarCacheEventService

* remove test console.log

* Fix type checks errors

* chore: remove pt comment

* add route.ts

* chore: fix tests

* Improve cache impl

* chore: update recurring event id

* chore: small improvements

* calendar cache improvements

* Fix remove dynamic imports

* Add cleanup stale cache

* Fix tests

* add event update

* type fixes

* feat: add comprehensive tests for new calendar subscription API routes

- Add tests for /api/cron/calendar-subscriptions-cleanup route (9 tests)
- Add tests for /api/cron/calendar-subscriptions route (10 tests)
- Add tests for /api/webhooks/calendar-subscription/[provider] route (11 tests)
- Add missing feature flags for calendar-subscription-cache and calendar-subscription-sync
- All 30 tests pass with comprehensive coverage of authentication, feature flags, error handling, and service instantiation

Tests cover:
- Authentication scenarios (API key validation, Bearer tokens, query parameters)
- Feature flag combinations (cache/sync enabled/disabled states)
- Success and error handling (including non-Error exceptions)
- Service instantiation with proper dependency injection
- Provider validation for webhook endpoints

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* feat: add comprehensive tests for calendar subscription services, repositories, and adapters

- Add unit tests for CalendarSubscriptionService with subscription, webhook, and event processing
- Add unit tests for CalendarCacheEventService with cache operations and cleanup
- Add unit tests for CalendarSyncService with Cal.com event filtering and booking operations
- Add unit tests for CalendarCacheEventRepository with CRUD operations
- Add unit tests for SelectedCalendarRepository with calendar selection management
- Add unit tests for GoogleCalendarSubscriptionAdapter with subscription and event fetching
- Add unit tests for Office365CalendarSubscriptionAdapter with placeholder implementation
- Add unit tests for AdaptersFactory with provider management and adapter creation
- Fix lint issues by removing explicit 'any' type casting and unused variables
- All tests follow Cal.com conventions using Vitest framework with proper mocking

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: improve calendar-subscriptions-cleanup test performance by adding missing mocks

- Add comprehensive mocks for defaultResponderForAppDir, logger, performance monitoring, and Sentry
- Fix slow test execution (933ms -> <100ms) caused by missing dependency mocks
- Ensure consistent test performance across different environments

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* Fix tests

* Fix tests

* type fix

* Fix coderabbit comments

* Fix types

* Fix test

* Update apps/web/app/api/cron/calendar-subscriptions/route.ts

Co-authored-by: Alex van Andel <me@alexvanandel.com>

* Fixes by first review

* feat: add database migrations for calendar cache and sync fields

- Add CalendarCacheEventStatus enum with confirmed, tentative, cancelled values
- Add new fields to SelectedCalendar: channelId, channelKind, channelResourceId, channelResourceUri, channelExpiration, syncSubscribedAt, syncToken, syncedAt, syncErrorAt, syncErrorCount
- Create CalendarCacheEvent table with foreign key to SelectedCalendar
- Add necessary indexes and constraints for performance and data integrity

Fixes database schema issues causing e2e test failures with 'column does not exist' errors.

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* only google-calendar for now

* docs: add Calendar Cache and Sync feature documentation

- Add comprehensive feature overview and motivation
- Document feature flags with SQL examples
- Include SQL examples for enabling features for users and teams
- Reference technical documentation files

Addresses PR #23876 documentation requirements

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* docs: update calendar subscription README with comprehensive documentation

- Undo incorrect changes to main README.md
- Update packages/features/calendar-subscription/README.md with:
  - Feature overview and motivation
  - Environment variables section
  - Complete feature flags documentation with SQL examples
  - SQL examples for enabling features for users and teams
  - Detailed architecture documentation

Addresses PR #23876 documentation requirements

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix docs

* Fix test to available calendars

* Fix test to available calendars

* add migration and sync boilerplate

* fix typo

* remove double log

* sync boilerplate

* remove console.log

* only subscribe for google calendar

* adjust for 3 months fetch

* only subscribe for teams that have feature enabled

* adjust tests

* chore: safe increment error count

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* calendar sync

* test: add comprehensive tests for CalendarSyncService

- Add comprehensive test coverage for CalendarSyncService methods
- Test handleEvents, cancelBooking, and rescheduleBooking functionality
- Cover edge cases like missing UIDs, malformed UIDs, and error handling
- Fix dynamic import usage in CalendarSyncService to use .default
- Remove invalid properties from handleNewBooking call to fix type errors

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: add skipCalendarSyncTaskCreation flag to handleCancelBooking to prevent infinite loops

- Add skipCalendarSyncTaskCreation field to bookingCancelSchema in zod-utils.ts
- Update handleCancelBooking to skip EventManager.cancelEvent when flag is true
- Update CalendarSyncService.cancelBooking to pass skipCalendarSyncTaskCreation: true
- Update CalendarSyncService.rescheduleBooking to pass skipCalendarSyncTaskCreation: true
- Update tests to verify the flags are passed correctly

This prevents infinite loops when calendar events are cancelled/rescheduled from
external calendars (Google/Office365) which trigger webhooks to Cal.com, which
would otherwise try to update the external calendar again.

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* refactor: rename flag to skipCalendarSyncTaskCancellation and use static imports

- Rename skipCalendarSyncTaskCreation to skipCalendarSyncTaskCancellation in handleCancelBooking
- Convert dynamic imports to static imports in CalendarSyncService
- Update tests to use vi.hoisted for proper mock hoisting with static imports

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* feat: add error handling and static import for handleNewBooking

- Create index.ts entry point for handleNewBooking directory
- Add try-catch error handling to cancelBooking and rescheduleBooking
- Log errors but don't block calendar sync operations
- Update tests to verify errors are caught and logged, not thrown

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* refactor: use RegularBookingService directly and fix safeStringify usage

- Remove handleNewBooking/index.ts and call getRegularBookingService().createBooking() directly in CalendarSyncService
- Fix safeStringify usage: apply to error itself, not wrapper object
- Update tests to mock getRegularBookingService instead of handleNewBooking

Addresses PR comments from Volnei and Cubic-dev-ai

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: restore handleNewBooking/index.ts and fix bookingData structure for calendar sync

- Restore handleNewBooking/index.ts as entry point for static imports
- Fix CalendarSyncService.rescheduleBooking to use correct bookingData structure
  with required fields (eventTypeId, start, end, timeZone, language, metadata)
- Use rescheduleUid to indicate this is a reschedule operation
- Fix safeStringify usage in error logging (wrap only the error, not the whole object)
- Update tests to match new bookingData structure

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* refactor: address PR comments - use RegularBookingService directly, remove unnecessary flags, fix booking reference update

- Remove handleNewBooking/index.ts wrapper and use getRegularBookingService().createBooking() directly in CalendarSyncService
- Remove allRemainingBookings and cancelSubsequentBookings flags from cancelBooking (only cancel the specific booking, not the entire series)
- Move bookingReference update outside skipCalendarSyncTaskCancellation block for data consistency
- Update tests to match new implementation

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* chore: remove unnecessary comment from zod-utils.ts

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* feat: add Sentry metrics telemetry and fix null assertions in CalendarSyncService

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: use dynamic import for getRegularBookingService to avoid RAQB import in server context

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* fix: use dynamic import for findTeamMembersMatchingAttributeLogic to avoid RAQB import in server context

Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>

* improve booking update

* add more tests and edge cases

* fix: add required actionSource and Sentry mocks to calendar sync

Add actionSource: "SYSTEM" to handleCancelBooking call after it became
required, and mock @sentry/nextjs in test files.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Alex van Andel <me@alexvanandel.com>
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-02-26 13:12:52 -03:00
5d65a0f091 fix: hide cal branding for orgs/teams (#27643)
* fix: hide branding for teams

* fix: remove unused organizationId and username fields from profiles select

Addresses Cubic AI review feedback (confidence 9/10) to select only
the profile fields that are actually used. The organizationId and
username fields were fetched but never referenced in this function.

Co-Authored-By: unknown <>

* fix: unit tests

* fix: add prisma named export to test mock

Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>

* Add tests: packages/features/profile/lib/hideBranding.test.ts

Generated by Paragon from proposal for PR #27643

* chore: implement cubic feedback

* fix: merge conflicts

* fix: unit tests

* fixup

* refactor: implement DI pattern for event type service

* fix: atoms build

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-25 20:53:01 +09:00
4081d11fbe feat: workflow auto translation (#27087)
* feat: workflow auto translation

* tests: add unit tests

* refactor: tests and workflow

* fix: type err

* fix: type err

* fix: remove redundant index on WorkflowStepTranslation

The @@index on [workflowStepId, field, targetLocale] duplicates the @@unique
constraint on the same columns. A unique index already provides efficient
lookups, so the separate @@index adds storage overhead and write latency
without benefit.

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* fix: correct locale mapping when translation API returns null

Map translations with their corresponding locales before filtering to
preserve correct locale-to-translation associations. Previously, filtering
out null translations would reindex the array, causing incorrect locale
mappings when any translation in the batch failed.

Also fixes pre-existing lint warnings:
- Move exports to end of file
- Add explicit return type to processTranslations
- Replace ternary with if-else for upsertMany selection

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* fix: address review feedback for workflow auto-translation

- Add change detection before creating translation tasks
- Rename userLocale to sourceLocale in task props for clarity
- Show source language in UI with new translation key
- Extract SUPPORTED_LOCALES to shared translationConstants.ts
- Fix locale mapping bug in translateEventTypeData.ts
- Add WhatsApp translation support
- Abstract translation lookup into shared translationLookup.ts helper
- Restore if-else readability for SCANNING_WORKFLOW_STEPS

Co-authored-by: Udit Takkar <udit.takkar@cal.com>
Co-Authored-By: unknown <>

* fix: update test to use sourceLocale instead of userLocale

Co-Authored-By: unknown <>

* refactor: feedback

* fix: handle first time

* fix: tests

* fix: tests

* fix: address Cubic AI review feedback (confidence 9/10 issues)

- WhatsApp translation: Apply variable substitution using getSMSMessageWithVariables
  and clear contentSid when using translated body to ensure Twilio uses the
  translated text instead of the original template

- update.handler.ts: Change sourceLocale assignment from ?? to || for consistency
  with tasker payload behavior (line 481)

- ITranslationService.ts: Rename methods from plural to singular naming:
  - getWorkflowStepTranslations -> getWorkflowStepTranslation
  - getEventTypeTranslations -> getEventTypeTranslation
  Updated all call sites and tests accordingly

Co-Authored-By: unknown <>

* fix: address Cubic AI review feedback (confidence 9/10+ issues)

- Fix getSMSMessageWithVariables to handle WHATSAPP_ATTENDEE action for
  locale and timezone (confidence 9/10)
- Remove WhatsApp translation feature that set contentSid to undefined
  since Twilio ignores body parameter for WhatsApp and requires
  pre-approved Message Templates (confidence 10/10)

Co-Authored-By: unknown <>

* fix: translatio

* Add tests: packages/features/eventTypeTranslation/repositories/EventTypeTranslationRepository.test.ts

Generated by Paragon from proposal for PR #27087

* Add tests: packages/features/tasker/tasks/translateWorkflowStepData.test.ts

Generated by Paragon from proposal for PR #27087

* chore: nit

* chore: verfied atg

* fix: set sourceLocale for new steps, add shouldDirty to checkbox, remove spec docs

- Set sourceLocale fallback in addedSteps mapping to fix stale detection mismatch
- Add { shouldDirty: true } to autoTranslateEnabled checkbox onChange
- Remove specs/workflow-translation/ directory (planning docs, not for repo)

Co-authored-by: Udit Takkar <udit.07.takkar@gmail.com>
Co-Authored-By: unknown <>

* chore: add specs back

* fix: type error

* fix: type error

* fix: type err

* fix: tests

* refactor: feedback

* fix: type err

* refactor

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <udit.takkar@cal.com>
Co-authored-by: Udit Takkar <udit.07.takkar@gmail.com>
2026-02-25 01:03:55 +05:30
f883dee084 perf: improve getTotalBookingDuration query (#27383)
* perf: improve getTotalBookingDuration query

* perf: improve getTotalBookingDuration query

* test: add unit tests for getTotalBookingDurationForUsers and yearly duration pre-fetching

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* fix: integration tests

* fix: update tests

* fix: use vi.stubEnv instead of direct process.env modification for test isolation

Replace direct deletion of process.env variables with vi.stubEnv() to ensure
automatic restoration after tests, preventing flaky tests and side effects
in parallel execution.

Issue identified by Cubic AI (confidence: 9/10)

Co-Authored-By: unknown <>

* chore: add log

* refactor: imports

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-24 22:55:33 +05:30
e3a9f54ba5 feat: Configure cancellation reason (#26872)
* feat: Configure cancellation reason

* fix: use enums

* tests: add unit tests

* fix: type error

* chore: remove duplicate dialog

* fix: type erro

* refator: improvements

* refator: improvements

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-24 13:35:51 -03:00
c9abc556ba fix: improve getIP header resolution for CF → Vercel setup (#28152)
Co-Authored-By: unknown <>

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-24 14:47:14 +00:00
Benny Joo 9855176948 refactor: Remove all TrpcSessionUser usages in @calcom/features (#27853)
* sessionUser in features

* update sessionMiddleware

* update

* format changes

* update import paths

* fix

* fix ts errors

* refactor

* fix

* fix

* fix

* fix

* rename

* rename

* rename

* use error with code objs
2026-02-24 09:29:54 +00:00
48cbb94af2 feat: add webhook trigger when routing form fallback route is hit (#27588)
* feat: add no users found fallback action for routing forms

- Add NoUsersFoundFallbackActionType enum with CustomPageMessage and ExternalRedirectUrl options
- Add noUsersFoundFallbackAction field to zodNonRouterRoute schema
- Add NoUsersFoundFallback UI component in RouteBuilder for configuring fallback action
- Update handleResponse to return noUsersFoundFallbackAction when no team members match
- Add i18n translation keys for new UI strings

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: change fallback to use same action options as main route

- Replace noUsersFoundFallbackAction with fallbackAction that has same structure as main action
- Add action dropdown and input fields to fallback attributes query builder section
- Support Event redirect, External URL, and Custom page options in fallback
- Remove separate NoUsersFoundFallback toggle component
- Update handleResponse to return fallbackAction

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: ensure fallbackAction type is always defined in onChange handlers

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add guards for route.fallbackAction in onChange handlers

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: only return fallbackAction when no users are found

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: restructure fallback section to mirror main route structure

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: ensure backwards compatibility for existing routes with fallbackAttributesQueryValue

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: initialize fallbackAction with main event type for backwards compatibility

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: include fallbackAction in getRoutesToSave to persist changes

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use fallbackAction in getRoutedUrl when no team members found

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use i18n for fallback label and add tests for fallback action

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: do not trigger fallback action when CRM contact owner is found

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: prioritize fallbackAction over fallbackAttributesQueryValue

When a route has a fallbackAction configured, skip the
fallbackAttributesQueryValue to ensure the fallbackAction is triggered
when no team members are found. This maintains backwards compatibility
by only using fallbackAttributesQueryValue when fallbackAction is not set.

Also treats teamMemberIdsMatchingAttributeLogic being null (routing couldn't
run, e.g., missing orgId) the same as an empty array for the purpose of
triggering the fallbackAction.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: extract RouteActionSelector shared component for action selection UI

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add i18n string for default custom page message

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add webhook trigger when routing form fallback route is hit

- Add ROUTING_FORM_FALLBACK_HIT to WebhookTriggerEvents enum in Prisma schema
- Add new trigger to routing-forms webhook triggers in constants
- Add translation string for the new webhook trigger
- Implement triggerFallbackWebhook function in formSubmissionUtils.ts
- Call webhook trigger from handleResponse.ts when fallback action is used

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: remove webhook object from error log to avoid exposing secrets

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* revert: remove webhook trigger changes (to be moved to separate PR)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add webhook trigger when routing form fallback route is hit

- Add ROUTING_FORM_FALLBACK_HIT to WebhookTriggerEvents enum in Prisma schema
- Add new trigger to routing-forms webhook triggers in constants
- Add translation string for the new webhook trigger
- Implement triggerFallbackWebhook function in formSubmissionUtils.ts
- Call webhook trigger from handleResponse.ts when fallback action is used

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: remove webhook object from error log to avoid exposing secrets

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add ROUTING_FORM_FALLBACK_HIT to PayloadBuilderFactory trigger mapping

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* style: apply biome formatting fixes

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: restore removed comments in RouteBuilder

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* chore: add prisma migration for ROUTING_FORM_FALLBACK_HIT enum value

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add ROUTING_FORM_FALLBACK_HIT to FormTriggerEvents type union

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: add test coverage for triggerFallbackWebhook function

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: consolidate fallback webhook firing with form submission webhooks

Move ROUTING_FORM_FALLBACK_HIT webhooks into the same Promise.all() batch
as FORM_SUBMITTED / FORM_SUBMITTED_NO_EVENT, eliminating redundant
getWebhooks/getWebhookTargetEntity/getOrgIdFromMemberOrTeamId calls.

- Add fallbackAction parameter to _onFormSubmission and onSubmissionOfFormResponse
- Remove triggerFallbackWebhook function and all its usages/imports
- Move getFallbackAction() earlier in handleResponse.ts and pass result through
- Update all tests to verify batched webhook behavior

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Add UI option for trigger

* feat: persist fallbackAction on queued form responses

When a routing form response is queued, the fallbackAction determined
during routing is now stored on the QueuedFormResponse record. When
the queued response is later converted to a real FormResponse, the
stored fallbackAction is passed to onSubmissionOfFormResponse so the
ROUTING_FORM_FALLBACK_HIT webhook fires correctly.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* test: add coverage for fallbackAction in queued form response flow

Verify that fallbackAction is persisted when queuing and passed through
to onSubmissionOfFormResponse when the queued response is converted.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-23 16:44:41 -05:00
8238d4ffcd fix: use WEBAPP_URL for booking confirmation redirects to fix localhost behind proxy (#28144)
Replace request.url with WEBAPP_URL from @calcom/lib/constants as the base URL
for NextResponse.redirect() in booking confirmation API routes. Behind a reverse
proxy, request.url resolves to http://localhost:3000 instead of the public domain.

Fixes #20358

Co-Authored-By: unknown <>

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-23 14:19:54 -03:00
0a84ce5c73 fix: use smsReminderNumber fallback for attendee phone in SMS reminders (#27942)
* SMS reminders not trigger

* addressed devin review

* Add tests: packages/features/ee/workflows/lib/service/scheduleLazySMSWorkflow.test.ts

Generated by Paragon from proposal for PR #27942

* Add tests: packages/features/ee/workflows/lib/reminders/reminderScheduler.smsLazy.test.ts

Generated by Paragon from proposal for PR #27942

* Add tests: packages/features/tasker/tasks/sendWorkflowSMS.test.ts

Generated by Paragon from proposal for PR #27942

* Add tests: packages/features/ee/workflows/lib/reminders/smsReminderManager.test.ts

Generated by Paragon from proposal for PR #27942

* Delete packages/features/ee/workflows/lib/reminders/reminderScheduler.smsLazy.test.ts

* fix: update sendWorkflowSMS tests to match refactored implementation

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix: use smsReminderNumber fallback for attendee phone in SMS workflows

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* revert: keep only scheduleSMSReminders.ts changes, revert all other files

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix: restore reminderScheduler.ts and smsReminderManager.ts to original branch state

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix: use smsReminderNumber fallback for attendee phone in WhatsApp reminders

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-23 17:35:51 +01:00
7e73d675d7 refactor: improve invoice.upcoming logging and add strategyName to billing strategies (#28143)
- Add strategyName property to ISeatBillingStrategy interface and all implementations
- Log which strategy handled the invoice.upcoming webhook (not just whether it applied)
- Always log strategy result (not just when applied=true) for better observability
- Rename highWaterMarkApplied to strategyApplied since applied covers multiple strategies

Co-Authored-By: unknown <>

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-23 15:57:13 +00:00
Benny Joo 648ad72a54 refactor: extract dedicated @calcom/i18n package (#28141) 2026-02-23 13:30:12 +00:00
f00be08e8c fix: order custom questions by event type bookingFields in BookingDetailsSheet (#28140)
Co-Authored-By: unknown <>

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-23 22:25:02 +09:00
Yuvraj Angad SinghandAnik Dhabal Babu f1e8e3fa58 fix(caldav): consistent UIDs and VTIMEZONE in iCalendar output (#28115)
* fix(caldav): use consistent UIDs and inject VTIMEZONE in iCalendar output

Two remaining CalDAV interop issues from #9485:

1. UID consistency: use the booking's canonical UID (event.uid) instead
   of always generating a new random UUID. CalDAV servers use UID as the
   event identifier — different UIDs cause duplicate calendar entries.

2. VTIMEZONE injection: the ics library generates UTC times with no
   VTIMEZONE block. CalDAV servers like Fastmail read this as UTC and
   send scheduling emails with wrong times. Per RFC 5545 §3.6.5,
   DTSTART with TZID requires a matching VTIMEZONE component. We now
   build a proper VTIMEZONE using binary-searched DST transitions for
   the event's year, handling Northern/Southern hemisphere correctly.

* fix: use pre-transition offset for VTIMEZONE DTSTART per RFC 5545

The DTSTART in VTIMEZONE components must represent the local time
interpreted with the pre-transition offset (TZOFFSETFROM), not the
post-transition offset. For example, US Eastern spring forward DTSTART
should be 02:00 (EST), not 03:00 (EDT).

* Remove comments on UID handling in createEvent

Removed comments about UID handling for calendar events.

* Revise injectVTimezone documentation

Update injectVTimezone function documentation to clarify UTC handling.

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2026-02-21 14:38:56 +00:00
Anirban SinghaandRomit 4dbe044ecc refactor: remove unused imports and stale TODO comment from caleventparser.ts (#28096)
* refactor: replace manual provider logic with getAppFromLocationValue

* chore: revert changes and remove stale comment

---------

Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-21 19:38:14 +05:30
Romit f1ae5f727a fix: update fast-xml-parser and ignore audit 1113407 (#28117) 2026-02-21 12:22:57 +00:00
Romit 7ee01c0487 fix (#28119) 2026-02-21 09:16:13 -03:00
05537780b8 fix: add biome overrides for embed-core to prevent auto-import of node:process (#27387)
* fix: use import.meta.env instead of process.env in embed.ts

Using import.meta.env is Vite's native way to handle environment variables
in browser bundles. This prevents biome from auto-adding 'import process
from node:process' which breaks the embed.js in browsers.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Remove unncessar comment

* fix: migrate remaining process.env to import.meta.env in embed.ts

Complete the migration started by @hariombalhara by also converting
process.env usages at lines 1681, 1682, and 1700 to import.meta.env.
Update env.d.ts to include EMBED_PUBLIC_EMBED_FINGER_PRINT,
EMBED_PUBLIC_EMBED_VERSION, and INTEGRATION_TEST_MODE types.

This ensures no process.env references remain in embed.ts, fully
preventing Biome from auto-adding import process from node:process.

Co-Authored-By: unknown <>

* fix: add biome overrides for embed-core to prevent auto-import of node:process

Reverts import.meta.env back to process.env since API V2's tsconfig uses
module: commonjs which doesn't support import.meta. Instead, adds biome
overrides for embed-core to disable useNodejsImportProtocol, noProcessEnv,
and noProcessGlobal rules that were causing biome to auto-add
'import process from node:process' on save.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-20 14:38:11 -03:00
Hariom BalharaandDevin AI 3e29904d7d test: add tests for __reloadInitiated behavior to ensure correct bookerViewed vs bookerReloaded events (#27379)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-20 14:35:18 -03:00
06f4b25080 fix: update routing form identifier hint text with learn more link (#27837)
* fix: update routing form identifier hint text with learn more link

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* UI improvements

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2026-02-20 13:09:09 +01:00
Deepanshu 79fc0c8437 fix: toolbar dropdown toggle (#28097) 2026-02-20 11:20:38 +00:00
a2b25fa615 fix: prevent deselecting active option in booker layout toggle (#27748)
* fix: prevent deselecting active option in ToggleGroup

Radix UI's single-type ToggleGroup allows deselection by default,
calling onValueChange("") when the active item is clicked.

Fix by converting to controlled mode with proper dual-mode support:
- Controlled (value prop): parent owns state, component just filters
  empty values from onValueChange. Parent can still reject changes.
- Uncontrolled (defaultValue prop): internal useState prevents
  deselection by only updating state for non-empty values.

* Update ToggleGroup.tsx

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
Co-authored-by: Eunjae Lee <hey@eunjae.dev>
2026-02-20 10:41:54 +00:00
14c151be76 fix: add CSRF protection to OAuth callback via HMAC-signed nonce (#28083)
* fix: add CSRF protection to OAuth callback via HMAC-signed nonce

The OAuth state parameter was used only for passing application data
(returnTo, teamId) with no cryptographic binding to the user session.
An attacker could authorize their own account on a provider, capture the
authorization code, and trick a logged-in user into visiting the callback
URL to link the attacker's account to the victim's Cal.com profile.

Changes:
- encodeOAuthState: generate a random nonce and HMAC-sign it with
  NEXTAUTH_SECRET + userId, injecting both into the OAuth state
- decodeOAuthState: verify the HMAC on callback using timingSafeEqual;
  skip verification when nonce is absent (backwards compatible with apps
  that don't yet use encodeOAuthState)
- Stripe callback: replace raw state.returnTo redirect with
  getSafeRedirectUrl to prevent open redirect, remove redundant
  getReturnToValueFromQueryState, add missing return on access_denied

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: make CSRF nonce verification mandatory with allowlist for exempt apps

Makes nonce/HMAC verification mandatory by default in decodeOAuthState,
preventing attackers from bypassing CSRF protection by omitting nonce
fields from the state parameter.

Apps not yet migrated to encodeOAuthState (stripe, basecamp3, dub,
webex, tandem) are explicitly allowlisted and pass their slug to
decodeOAuthState to skip verification.

Addresses review feedback (identified by cubic) about the conditional
check being trivially bypassable.

Co-Authored-By: unknown <>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-20 10:35:01 +00:00
1aae57daae refactor(booking-audit): discriminated union for displayFields and i18n param support (#27373)
* feat: Add infrastructure for no-show audit integration

- Add Prisma migrations for SYSTEM source and NO_SHOW_UPDATED audit action
- Add NoShowUpdatedAuditActionService with array-based attendeesNoShow schema
- Update BookingAuditActionServiceRegistry to include NO_SHOW_UPDATED
- Update BookingAuditTaskConsumer and BookingAuditViewerService
- Add AttendeeRepository methods for no-show queries
- Update IAuditActionService interface with values array support
- Update locales with no-show audit translation keys

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Add NO_SHOW_UPDATED to BookingAuditAction and SYSTEM to ActionSource types

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED from BookingAuditAction type to match Prisma schema

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update BookingAuditActionSchema to use NO_SHOW_UPDATED instead of HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Remove deprecated no-show audit services and unify to NoShowUpdatedAuditActionService

- Delete HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService
- Update BookingAuditProducerService.interface.ts to use queueNoShowUpdatedAudit
- Update BookingAuditTaskerProducerService.ts to use queueNoShowUpdatedAudit
- Update BookingEventHandlerService.ts to use onNoShowUpdated
- Add integration tests for NoShowUpdatedAuditActionService

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Add data migration step for deprecated no-show enum values

Addresses Cubic AI review feedback (confidence 9/10): The migration now
includes an UPDATE statement to convert existing records using the
deprecated 'host_no_show_updated' or 'attendee_no_show_updated' enum
values to the new unified 'no_show_updated' value before the type cast.
This prevents migration failures if any existing data uses the old values.

Co-Authored-By: unknown <>

* fix: Use CASE expression in USING clause for enum migration

Fixes PostgreSQL error 'unsafe use of new value of enum type' by avoiding
the ADD VALUE statement and instead using a CASE expression in the ALTER
TABLE USING clause to convert deprecated enum values (host_no_show_updated,
attendee_no_show_updated) to the new unified value (no_show_updated) during
the type conversion.

Co-Authored-By: unknown <>

* fix: Replace hardcoded color with semantic text-success class

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove color class completely from display fields

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: Add valuesWithParams support for translatable complex field values

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor(booking-audit): use discriminated union for displayFields and update consumers

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add explicit return type to getBookingHistoryHandler to bust stale tRPC build cache

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: replace $t() nested interpolation with separate translation keys and add translationsWithParams tests

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-20 14:34:12 +05:30
Abir RoyandSahitya Chandra 12e95a1f47 feat: Add meta pixel conversion events (#25638)
* feat(meta-pixel): add trackingEvent to zod schema

* fix: do not allow trackingEvent to be optional

* feat(meta-pixel): add trackingEvent selection dropdown to UI

* feat(meta-pixel): add trackingEvent to Event Type App Data

* fix(meta-pixel): implement history API hook for SPA conversion tracking

* fix(meta-pixel): check for cancel in URL and prevent Re-wrapping of pushState

* Update EventTypeAppSettingsInterface.tsx

* fix: make trackingEvent optional in zod schema to fix type-check

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-02-20 00:17:42 +05:30
60b6086221 feat: add keyboard shortcuts and tooltips to booking slideover buttons (#27428)
* feat: add keyboard shortcuts and tooltips to booking slideover buttons

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: remove duplicate useBookingLocation import and fix import ordering

- Removed duplicate import of useBookingLocation from non-existent
  @calcom/web/modules/bookings/hooks/useBookingLocation path
- Fixed import ordering to satisfy biome organizeImports rules
- Removed unnecessary code comment
- Original feature by @PeerRich via Devin AI

Co-Authored-By: unknown <>

* use same style arrows for both button and remove bydefault focus from them

* fix join button tooltip hover

* fix: disable keyboard shortcuts when overlays/dialogs are open on BookingDetailsSheet

Co-Authored-By: unknown <>

* fix: use focus-based detection instead of selector-based overlay detection for keyboard shortcuts

Co-Authored-By: unknown <>

* fix: allow keyboard shortcuts when focus is on sheet ancestors

Co-Authored-By: unknown <>

* fix: use capture phase for keyboard handler to prevent Enter from activating focused buttons

Co-Authored-By: unknown <>

* fix: allow shortcuts when focus is on page elements outside any Radix portal

Co-Authored-By: unknown <>

* fix: handle calendar event clicks in onInteractOutside to prevent sheet close/reopen

Co-Authored-By: unknown <>

* fix: stop arrow key propagation to prevent Radix dropdown from opening during booking navigation

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: always stop arrow key propagation when sheet is active, even at first/last booking

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: extract keyboard handler into testable utility with tests

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: resolve type errors in keyboard handler config and test mocks

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* test: add e2e tests for booking sheet keyboard shortcuts

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: replace text= locators with data-testid selectors in e2e tests

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* made 3 fixes: Fix 1 — Stabilize handleNext/handlePrevious/handleClose with useCallback
In BookingDetailsSheet.tsx, all three handler functions were plain arrow functions recreated on every render, causing the useEffect to tear down and re-attach the document keydown listener unnecessarily. Wrapped all three in useCallback with proper dependency arrays (the Zustand store functions they call).
Fix 2 — data-booking-list-item verified (no change needed)
Confirmed that data-booking-list-item is rendered on BookingListItem.tsx and data-booking-calendar-event is rendered on Event.tsx. The onInteractOutside handler in the final merged state correctly checks both selectors. No code change required.
Fix 3 — Removed dead code from JoinMeetingButton
Reverted JoinMeetingButton back to a plain function component:
Removed forwardRef wrapping (no caller passes a ref)
Removed showTooltip prop (unused — tooltip is handled by the parent BookingDetailsSheet)
Removed ref prop from the inner Button
Removed unused Tod forwardRef imports

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
Co-authored-by: eunjae@cal.com <hey@eunjae.dev>
Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
2026-02-19 22:32:43 +05:30
5d65df9c05 chore: migrate booking requested webhook trigger (#27546)
* init

* wiring up

* fix type

* feat: implement DI pattern for webhook producer in API v2

- Export IWebhookProducerService and getWebhookProducer from platform-libraries
- Add WEBHOOK_PRODUCER token and useFactory provider in RegularBookingModule
- Inject webhookProducer in RegularBookingService and pass to base class

This follows the composition root pattern where only the NestJS module
knows about getWebhookProducer(), and all consumers depend only on the
IWebhookProducerService interface via constructor injection.

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* test: migrate BOOKING_REQUESTED tests to new webhook architecture

- Remove failing BOOKING_REQUESTED tests from fresh-booking.test.ts (4 tests)
- Remove failing BOOKING_REQUESTED tests from reschedule.test.ts (2 tests)
- Remove failing BOOKING_REQUESTED test from collective-scheduling.test.ts (1 test)
- Replace WebhookTaskConsumer.test.ts with placeholder (constructor changed)
- Create new webhook architecture test suite:
  - producer/WebhookTaskerProducerService.test.ts (14 tests)
  - consumer/WebhookTaskConsumer.test.ts (8 tests)
  - consumer/triggers/booking-requested.test.ts (8 tests)

The new test suite is organized by trigger type for extensibility as more
triggers are migrated to the producer/consumer pattern.

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* test: remove paid events BOOKING_REQUESTED test (moved to new architecture)

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* wrap webhook in own try-catch

* wire datafetcher

* fix

* fix v2

* fix circular dependency

* --

* merge-conflict-resolve

* mreg-conflict-resolve

* remove early return

* test: add integration tests for BOOKING_REQUESTED webhook producer invocation

Cover all 8 scenarios verifying the booking flow correctly invokes
the webhook producer for BOOKING_REQUESTED:

1. Basic confirmation → queueBookingRequestedWebhook called
2. Booker-is-organizer + confirmation → still called
3. Confirmation threshold NOT met → not called (BOOKING_CREATED instead)
4. Confirmation threshold IS met → called
5. Paid event + confirmation → called after payment succeeds
6. Reschedule + confirmation (non-organizer) → called (not BOOKING_RESCHEDULED)
7. Reschedule + confirmation (organizer) → not called (BOOKING_RESCHEDULED instead)
8. Collective scheduling + confirmation → called

Adds reusable MockWebhookProducer helper in @calcom/testing for
extendable use as more webhook triggers migrate to the new architecture.

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix bug

* fix conditional check

* remove unnecessary comment

* add missing expect

* remove empty test

* clean up

* tasker config

* --

* fix missing metadata

* remove faulty if else

* test: add payload content verification tests for BOOKING_REQUESTED webhook

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* remove unnecessary tests

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Hariom Balhara <1780212+hariombalhara@users.noreply.github.com>
2026-02-19 20:21:26 +04:00
Peer RichelsenandDevin AI 66ce20245c docs: declare credentials and environment variables in calcom-api skill (#28047)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-19 14:32:41 +00:00
c321a6c07a feat: owner can test non accepted OAuth client (#27525)
* refactor: combine exchange and refresh into token endpoint

* refactor: controller error handling

* refactor: use snake_case

* refactor: use snake_case

* refactor: use snake case

* refactor: token endpoint accepts application/x-www-form-urlencoded

* refactor: token endpoint accepts application/x-www-form-urlencoded

* refactor: flat token response data

* refactor: error structure

* refactor: client_id in the body

* fix: address Cubic AI review feedback on OAuth2 endpoints

- Fix getClient endpoint to use proper REST API error format instead of OAuth token error format (confidence 9/10)
- Add missing space after comma in error format string in token.input.pipe.ts (confidence 9/10)
- Support both camelCase and snake_case inputs in authorize endpoint for backward compatibility (confidence 10/10)
- Restore legacy /exchange and /refresh endpoints alongside new /token endpoint for backward compatibility (confidence 10/10)
- Add OAuth2TokensResponseDto for legacy endpoint wrapped responses
- Add OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput for legacy endpoints

Co-Authored-By: unknown <>

* fix: address additional Cubic AI feedback on OAuth2 endpoints

- Log errors when status code >= 500 in handleClientError (confidence 9/10)
- Add Cache-Control: no-store and Pragma: no-cache headers to legacy /exchange and /refresh endpoints (confidence 9/10)

Co-Authored-By: unknown <>

* docs

* Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints"

This reverts commit 39cc4aa3ebb9e59a171541d7010398425995ed89.

* Revert "fix: address Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 97bf593186db04c0859f9ca30950c9e3e524019d.

* docs

* fix: address Cubic AI review feedback on OAuth2 endpoints

- Fix getClient to use handleClientError instead of handleTokenError (confidence 10)
- Restore legacy /exchange and /refresh endpoints for backward compatibility (confidence 9)
- Fix RFC 6749 error format: use human-readable messages in error_description (confidence 9)
- Fix errorDescription in OAuthService to use OAUTH_ERROR_REASONS mapping (confidence 9)

Co-Authored-By: unknown <>

* fix: address additional Cubic AI feedback on OAuth2 endpoints

- Fix security issue: Replace 'CALENDSO_ENCRYPTION_KEY is not set' with generic 'Internal server configuration error' message (confidence 10/10)
- Fix backward compatibility: Create OAuth2LegacyTokensDto with camelCase properties for legacy /exchange and /refresh endpoints (confidence 9/10)
- Skipped: RFC 6749 error field issue (confidence 8/10, below threshold)

Co-Authored-By: unknown <>

* e2e

* Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints"

This reverts commit a080e93f07aaf5a7dcf81fe605012cb7ebcdc192.

* Revert "fix: address Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 04986a16c981521ca97069152457bf521a9ee45f.

* fix: re-apply Cubic AI review feedback on OAuth2 endpoints

- Restore OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput classes
- Restore legacy /exchange and /refresh endpoints in OAuth2Controller
- Restore OAuth2LegacyTokensDto and OAuth2TokensResponseDto classes
- Restore OAUTH_ERROR_DESCRIPTIONS mapping in oauth2-error.service.ts
- Restore OAUTH_ERROR_REASONS lookup in OAuthService.ts mapErrorToOAuthError
- Fix encryption_key_missing error to not expose internal env var name

Addresses Cubic AI feedback with confidence >= 9/10:
- Comment 32 (9/10): Legacy endpoints and input classes
- Comment 34 (9/10): Error description mapping in OAuthService
- Comment 35 (10/10): OAUTH_ERROR_DESCRIPTIONS in error service

Skipped (confidence < 9/10):
- Comment 33 (8/10): getClient handleTokenError vs handleClientError

Co-Authored-By: unknown <>

* Revert "fix: re-apply Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 416bef9c931d9a7ed78c65a70a3425550d61b151.

* delete unused file

* fix: e2e tests

* address cubic review

* fix: address Cubic AI review feedback on OAuth2 exception filter

- Fix header case sensitivity: use lowercase 'x-request-id' instead of 'X-Request-Id' since Express lowercases all request headers
- Redact request body in error logs to prevent exposing sensitive OAuth2 credentials like client_secret, password, and refresh_token

Co-Authored-By: unknown <>

* docs: api v2 oauth controller docs

* chore: remove authorize endpoint

* feat: owner can test non accepted OAuth client

* fix: remove sensitive data from OAuth2 exception logs

Remove Authorization header and userEmail from error logs in
OAuth2HttpExceptionFilter to avoid logging sensitive information.

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* fix: e2e

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-19 08:11:46 -03:00
0eb2c15b39 fix: handle JSON string name field from URL prefill for firstAndLastName variant (#28039)
* fix: handle JSON string name field from URL prefill for firstAndLastName variant

* refactoring logic

* improve test coverage

* remove unnecessary comment

---------

Co-authored-by: Maks Pikov <mixelburg@users.noreply.github.com>
Co-authored-by: Romit <romitgabani1.work@gmail.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-19 05:14:51 +05:30
9d29055808 feat: replace admin API settings page with link to API docs (#28046)
* feat: replace admin API settings page with link to API docs

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* chore: remove unused AdminAPIView component

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: rename admin API tab to API Docs

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-18 17:12:24 -05:00
74f3608b42 fix: Billings page reorganised (#28053)
* billings page reorganised

* Update redirect-apps.generated.ts

* small border update

* udpate for organization billing page

---------

Co-authored-by: Romit <romitgabani1.work@gmail.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-18 21:50:38 +00:00
9bfa4165b9 fix: prevent sending raw errors in responses (#24282)
* fix: prevent sending raw errors in responses

* correct already existing typo

* style: fix import ordering per biome lint

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-19 02:43:14 +05:30
cal-com-ci[bot]andLingo.dev 8a96a45424 feat: update translations via @LingoDotDev (#27639)
Co-authored-by: Lingo.dev <support@lingo.dev>
2026-02-18 16:32:10 -03:00
Deepanshu 0787c4890e fix: add toggle in workflow form (#27983) 2026-02-18 18:39:11 +01:00
Eunjae Lee 51e902f03e chore: pause syncing rules to devin (#28041)
* chore: pause syncing rules to devin

* Revert "chore: pause syncing rules to devin"

This reverts commit dd0e55322fe079b62207c9a4b58c9d24ce1c0dda.

* disable temporarily
2026-02-18 16:35:45 +00:00
Anirban SinghaandSahitya Chandra 9b1bf29ecf chore: remove stale Vitest workspace TODO (#27667)
Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-02-18 14:50:58 +00:00
Hariom BalharaandDevin AI ad65fbbd81 fix: change URL prefill behavior to skip only invalid fields (#26982)
* fix: change URL prefill behavior to skip only invalid fields

Previously, when prefilling booking form fields from URL query parameters,
if any single field failed validation, all prefilling was skipped and an
empty object was returned.

This change modifies the behavior so that only invalid fields are skipped,
while valid fields are still prefilled. The implementation:

- Adds validateSingleFieldForPrefill() to validate individual fields
- Adds parseFieldByField() to collect valid fields when full parse fails
- Modifies getBookingResponsesPartialSchema to use field-by-field parsing
  as a fallback when full schema validation fails
- Logs which specific fields were skipped and why

This improves user experience by preserving valid prefill data even when
some fields have invalid values.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: reduce code duplication in partial prefill validation

Simplify the implementation by integrating field-by-field error handling
directly into the existing preprocess() function instead of using separate
helper functions.

Changes:
- Remove validateSingleFieldForPrefill() and parseFieldByField() functions
- Simplify getBookingResponsesPartialSchema to directly use preprocess()
- Add try-catch wrapper in preprocess() when isPartialSchema=true
- Continue processing other fields even if one fails during preprocessing
- Log skipped fields with reasons at debug level

This reduces code duplication while maintaining the same behavior of
skipping only invalid fields during URL prefill.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fixes

* refactor: rename getRefinedValue to superRefineField and add edge case tests

- Rename getRefinedValue to superRefineField for clarity
- Remove duplicate multiselect test block
- Add test for empty object name field during partial prefill
- Add test for invalid URL format during partial prefill
- Add test for null responses during partial prefill

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Simplifu

* Simplif more

* Enhance booking responses schema tests to validate required fields and name variants. Updated error handling for empty names and added tests for first and last name requirements. Refactored schema validation logic to improve clarity and maintainability.

* fix types

* test: add test for email validation behavior during partial prefill

Documents that email validation is relaxed to z.string() during partial prefill,
consistent with phone field behavior where partial values like '+91' are accepted.
This addresses Cubic AI feedback (confidence 9/10) to verify email handling.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix

* Add tests: packages/features/bookings/lib/getBookingResponsesSchema.test.ts

Generated by Paragon from proposal for PR #26982

* Revert "Add tests: packages/features/bookings/lib/getBookingResponsesSchema.test.ts"

This reverts commit fc2b7ad7ca8099bc4f68e97b383ea16b41cdd772.

* Simplify

* fix: sanitize partial prefill log to avoid exposing user input data

Replaced raw Zod issues array in console.warn with a count of
validation errors to prevent sensitive user data from being logged.

Issue identified by cubic (confidence 9/10).

Co-Authored-By: unknown <>

* fix

* Remove throw Error

* Refactor booking responses schema tests to use helper functions for assertions

- Introduced `expectResponsesToBe` and `expectParsingToFail` helper functions to streamline test assertions.
- Replaced direct assertions with these helper functions for improved readability and maintainability.
- Removed redundant error handling code to simplify test logic.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-18 20:01:23 +05:30
eef47ddefd feat: add duplicate functionality for managed event types (#26792)
* feat: add duplicate functionality for managed event types

Co-Authored-By: peer@cal.com <peer@cal.com>

* feat: add disclaimer and redirect for managed event type duplication

- Add info alert disclaimer in duplicate modal for managed event types
- Pass schedulingType to duplicate dialog via query params
- Redirect to assignment tab after duplicating managed event types
- Add translation key for managed event type duplicate disclaimer

Co-Authored-By: peer@cal.com <peer@cal.com>

* test: add tests for managed event type duplication

Co-Authored-By: peer@cal.com <peer@cal.com>

* refactor: replace PrismaMock unit test with Prisma integration test for duplicate handler (#27973)

* refactor: replace PrismaMock unit test with Prisma integration test for duplicate handler

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: re-throw TRPCErrors in duplicate handler catch block and assert specific error codes in tests

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Hariom Balhara <1780212+hariombalhara@users.noreply.github.com>
Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>
2026-02-18 16:49:23 +04:00
8908a66c23 fix: allow booking rejection via GET for email clients that do not support forms (#28029)
* fix: allow booking rejection via GET for email clients that do not support forms

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* Refactor test cases for GET handler in route.test.ts

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-18 17:23:42 +05:30
Alex van AndelandDevin AI a78a3ffe39 refactor: optimize team booking limits query with in-app filtering (#28021)
Replace 3 sequential queries (with expensive attendee email IN clauses)
with 2 parallel queries using indexed eventType.teamId filtering and
in-application user filtering with Sets for O(1) lookups.

Fix managed events booking-limit behavior: managed bookings now only
match by organizer userId (not attendee email), preserving the original
query semantics where managed bookings used userId-only matching.

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-18 11:47:30 +00:00
a6a428c8cb feat: make actionSource required with ValidActionSource type across booking handlers (#27869)
* feat: make actionSource required with ValidActionSource type across booking handlers

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: update getAuditActionSource to return ValidActionSource, default to SYSTEM

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: revert getAuditActionSource, handleSeats, RegularBookingService back to ActionSource

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2026-02-18 07:34:25 -03:00
Pasquale Vitiello 217c6e6a76 chore: re-pull coss-ui components (#28032) 2026-02-18 10:08:35 +00:00
b1eb5a2809 feat: api v2 POST booking attendees endpoint (#27759)
* feat: add booking attendee endpoint

* chore: add attendee added email for add guests handler

* cleanup

* fix: restore BookingPbacGuard to prevent IDOR vulnerability in booking attendees endpoint

Co-Authored-By: unknown <>

* chore: implement review feedback, add a core service for booking attendees endpoint

* chore: implement PR feedback

* fix: dont reuse add guests handler instead add logic to add attendee function

* fix: revert previous changes

* chore: implement cubic feedback

* fix: e2e tests

* fix: e2e tests

* fix: remove convertTRPCErrorToErrorWithCode not needed

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-17 20:46:18 +00:00
Anirban Singha bd5d94a4ba fix: localize remaining hardcoded strings in PayPal setup (#27908)
* chore: add en locale key-value for paypal setup

* fix: add translation function for paypal setup

* chore: avoid merge conflicts
2026-02-17 17:36:45 +00:00
Shrey-SutariyaandRomit 3cfe295ed5 Commit 1 (#28011)
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-17 16:51:21 +00:00
20dcef6680 fix: validate schedule title input to block invalid characters (#27818)
* fix(availability): validate schedule title input to block invalid characters

* fix: add english translation for invalid_characters_in_name

* fix(schedule): allow Unicode characters in schedule name validation

* fix(schedule): update validation message to match regex

* fix: tsconfig target

* fix(schedule): add required validation in NewScheduleButton using translation

* fix(schedule): allow ASCII apostrophe in schedule name validation

* Update ScheduleListItem.tsx

* fix: remove unused @ts-expect-error directives

* fix: remove tsconfig target change

* Revert "fix: remove tsconfig target change"

This reverts commit d4992caf9b71cdfe32ac9db9a509128548097a30.

* Revert "fix: remove unused @ts-expect-error directives"

This reverts commit 913eda500aeccdd67b15cf1898f6db376bf3dda9.

* fix: update validation regex to support unicode characters

* fix: remove es6 from tsconfig

* Update NewScheduleButton.tsx

---------

Co-authored-by: Deepanshu Verma <deepanshuverma186@email.com>
Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-02-17 22:12:38 +05:30
11b65b295b test: add missing negation operator tests for TEXT, NUMBER, and compound rules (#27690)
* Fix exclusion filter - include all team members

* Fix display when members aren't saved in the DB

* Update tests

* test: add missing negation operator tests for TEXT, NUMBER, and compound rules

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: revert non-intentional changes to AddMembersWithSwitch.tsx

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2026-02-17 15:45:36 +00:00
4c73695d3a fix: refresh slots on timezone change for booker timezone restrictions (#27491)
* fix: refresh slots on timezone change for booker timezone restrictions

* refactor: use useMemo for timezone change detection

* revert: remove unnecessary formatting changes

* feat: add timezone refresh for platform components

Add timezone change detection and slot refresh to BookerPlatformWrapper
and EventTypeCalendarViewComponent to handle restriction schedules with
useBookerTimezone enabled.

* refactor: extract timezone slot refresh logic into reusable hook

* Update packages/platform/atoms/calendar-view/EventTypeCalendarViewComponent.tsx

Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>

* Update packages/platform/atoms/calendar-view/EventTypeCalendarViewComponent.tsx

Co-authored-by: Syed Ali Shahbaz <52925846+alishaz-polymath@users.noreply.github.com>

* fix

* fix: prevent unnecessary getSchedule calls when useBookerTimezone is disabled

* fix: add timezone fields to BookerEvent type

* fix: add missing properties to BookerEvent and BookerEventProfile types

* trying to fix type errors

* Add restrictionScheduleId and useBookerTimezone fields

* fix: correct import path for useBookerTime hook

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: explicitly include restrictionScheduleId and useBookerTimezone in getPublicEvent return

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* chore: trigger fresh CI build

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: cast event.data to BookerEvent for timezone fields access

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* refactor: address review feedback for timezone slot refresh

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* refactor: add explicit return type to event handler to ensure type propagation

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* refactor: extract useStableTimezone hook and remove dead timezone detection code

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

---------

Co-authored-by: hackice20 <yashkam431@gmail.com>
Co-authored-by: Yash <116657771+hackice20@users.noreply.github.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-17 07:46:40 -03:00
Raihanullah Shamsi ab4eff1fe1 fix: translate hardcoded 'mins' on payment page (#27998) 2026-02-17 09:26:25 +00:00
38b43f75ba refactor: remove circular dependencies from CalendarView atom (#27850)
* fix: decouple large calendar from features

* fix: move calendar to features since this is the better approach

* chore: move OOO slots to features

* feat: add DefaultOutOfOfficeSlot fallback for calendar OOO rendering

Co-Authored-By: rajiv@cal.com <sahalrajiv6900@gmail.com>

* chore: cleanup unused LargeCalendar component

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-17 08:14:33 +00:00
Hariom Balhara 9603831def refactor: update BookingHistory component to use date-fns for timestamp formatting (#27851)
Replaced dayjs with date-fns for better performance and consistency in date handling. Added Tooltip for displaying formatted timestamps and improved search functionality by translating field labels and values. Cleaned up code for better readability.
2026-02-17 13:22:16 +05:30
2bc17313fd fix: deep link reschedule audit log to booking drawer history tab (#27709)
* fix: deep link reschedule audit log to booking drawer history tab

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: make booking drawer tab-agnostic for cross-tab deep links

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use status-agnostic /bookings URL for audit log deep links

- Update audit service URLs from /bookings/upcoming?uid=... to /bookings?uid=...
- Add /bookings/page.tsx redirect that routes to /bookings/upcoming preserving query params
- Update tests to expect new URL format

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fixes

* refactor: use client-side replaceState instead of server redirect for booking deep links

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use router.replace instead of replaceState to update tab and booking list

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* improvements

* refactor: extract deep link logic from BookingListContainer into usePreSelectedBooking hook

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use proper BookingOutput status type in test helper

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: decouple getTabForBooking from BookingOutput type for simpler testing

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: accept Date | string for endTime in BookingForTabResolution interface

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: eliminate initialBookingUid prop drilling and revert formatting-only changes

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use AuditDeepLink wrapper to preserve target=_blank through ServerTrans cloneElement

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Improve code organization

* refactor: rename usePreSelectedBooking to useSwitchToCorrectStatusTab

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: push preSelectedBooking into store so drawer opens on direct navigation

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fixes

* fixes

* fixes

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Udit Takkar <53316345+Udit-takkar@users.noreply.github.com>
2026-02-17 13:20:06 +05:30
3a7122d613 fix: revert assignmentReason breaking change in webhook payloads (#27891)
* fix: revert assignmentReason breaking change in webhook payloads

Remove the new { category, details } format from EventPayloadType to
maintain backward compatibility for webhook consumers. The new format
is stripped at all webhook payload construction sites by destructuring
assignmentReason out of CalendarEvent before spreading into the payload.

A sanitizeAssignmentReasonForWebhook function provides an additional
safety net in sendPayload itself. Emails and booking single view
continue to use the new format via CalendarEvent.

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: strip assignmentReason from handlePaymentSuccess webhook payload

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: strip assignmentReason from triggerWebhooks and handleSeats webhook payloads

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* refactor: use zod safeParse instead of type assertion in sanitizeAssignmentReasonForWebhook

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-16 21:55:10 -03:00
Eunjae LeeandClaude Opus 4.6 21d28c9747 refactor: apply biome formatting to packages/trpc (#27928)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-16 12:46:42 -03:00
Volnei MunhozandDevin AI f8a93414a5 chore: remove companion app (moved to calcom/companion) (#27957)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-16 10:08:24 -03:00
DeepanshuandDeepanshu Verma 85e1ed3ab5 refactor: move cancel logic from inline onClick handler to dedicated function (#27972)
* refactor: move cancel booking logic into handleCancel function

* chore: remove unused comments per review feedback

---------

Co-authored-by: Deepanshu Verma <deepanshuverma186@email.com>
2026-02-16 09:46:42 +00:00
emrysal 4647333839 chore: release v6.2.0 2026-02-16 01:36:08 +00:00
Aritra Dey 9d4cb08c55 fix: Correct hours-to-days conversion in convertToNewDurationType (#27964)
Signed-off-by: Aritra Dey <adey01027@gmail.com>
2026-02-15 21:01:00 +05:30
Peer RichelsenandDevin AI 773fab858f fix: hide bookings opt-in banner on mobile viewport (#27965)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-15 14:24:21 +00:00
Aritra DeyandRomit ea0c92a267 fix: use maxLength parameter in truncateOnWord instead of hardcoded value (#27961)
Signed-off-by: Aritra Dey <adey01027@gmail.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-15 09:51:53 +00:00
Dhairyashil Shinde 2abefc412c update version (#27952) 2026-02-14 14:36:43 +00:00
Volnei MunhozandDevin AI 9d4b12b8d3 fix: lazy-load companion iframe to avoid requests on every page visit (#27946)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-14 11:41:43 +01:00
Anik Dhabal Babu c21281a55c preserve customReplyToEmail (#27941) 2026-02-13 18:09:39 +00:00
sean-brydon f5a813f531 Revert "revert (#27933)" (#27938)
This reverts commit 227ed64b49.
2026-02-13 23:36:50 +05:30
Dhairyashil Shinde fa53f54815 feat(companion): add configurable landing page (#27267)
* feat(companion): add configurable landing page feature

- Add useUserPreferences hook for persistent storage of landing page preference
- Add LandingPagePicker component for both iOS and Android/web platforms
- Update tabs index to redirect based on user preference
- Update bookings index to accept initial filter from URL params
- Add App Settings section in More screen with landing page selector
- Clear user preferences on logout for fresh state

* fix(companion): remove try-finally for React Compiler compatibility

* fix(companion): use router.replace for dynamic landing page redirect

Replace Redirect component with router.replace() to fix TypeScript
strict typing issue with expo-router's Href type for dynamic routes.

* fix(companion): use literal route strings for TypeScript strict typing

Use switch statement with literal route strings instead of dynamic
string variable to satisfy expo-router's strict Href type checking.

* working fix

* better css
2026-02-13 11:28:42 -03:00
Pedro Castro f07bed1a2a chore(deps): bump axios to 1.13.5 (#27864)
* chore: bump axios to 1.13.5

* chore: bump axios in apps/api/v2

* chore: dedupe follow-redirects to 1.15.11
2026-02-13 22:08:49 +09:00
sean-brydon 227ed64b49 revert (#27933) 2026-02-13 12:14:08 +00:00
Alex van AndelandDevin AI 237d7e95c4 fix: inline package.json descriptions in app-store _metadata.ts to fix Vitest RPC errors (#27931)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 08:41:39 -03:00
Eunjae LeeandDevin AI 896dfd50fd fix: prevent BookingDetailsSheet flicker when switching bookings (#27894)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 11:53:22 +01:00
Eunjae LeeandClaude Opus 4.6 e2119879ae refactor: apply biome formatting to packages/sms, prisma, emails, lib (#27880)
* refactor: apply biome formatting to small packages + packages/lib

Format packages/sms, packages/prisma, packages/platform/libraries,
packages/platform/examples, packages/platform/types, packages/emails,
and packages/lib.

Excludes packages/platform/examples/base/src/pages/[bookingUid].tsx
due to pre-existing lint errors.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* revert: remove packages/platform formatting changes

Revert biome formatting for packages/platform as requested.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-13 07:39:01 -03:00
7aefefc31f feat: enable onboarding-v3 globally and update e2e tests (#27922)
* feat: enable onboarding-v3 globally and update e2e tests

- Add migration to set onboarding-v3 feature flag enabled=true
- Rewrite onboarding.e2e.ts for v3 flow (Plan Selection → Personal Settings → Calendar)
- Update URL assertions in signup, team-invitation, org-invitation, ab-tests-redirect, and auth tests to accept both old and new onboarding paths

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix: use pathname-only matching in waitForURL to prevent false matches on callbackUrl query param

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* use test IDs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2026-02-13 10:37:47 +00:00
1b6b91b0ad fix: display phone numbers and localized timezone in BookingDetailsSheet (#27909)
* fix: display phone numbers and localized timezone in BookingDetailsSheet

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: replace selectAll with explicit column selects for Attendee query

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* Update apps/web/modules/bookings/components/BookingDetailsSheet.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Add tests: packages/lib/dayjs/formatToLocalizedTimezone.test.ts

Generated by Paragon from proposal for PR #27909

* Revert "refactor: replace selectAll with explicit column selects for Attendee query"

This reverts commit f810ba801c900c8f065e5e1ce1d02a1700322257.

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-02-13 10:27:01 +00:00
50c7210d6b fix: resolve signup watchlist review issues and auto-unlock on SIGNUP entry removal (#27923)
* fix: resolve signup watchlist review issues with deleteEntry, email verification ordering, and unlock flow

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: scope sendEmailVerification to non-invite signups only

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* feat: auto-unlock users when SIGNUP-source watchlist entries are removed

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

* fix: remove PII from error logging in unlockSignupUser

Co-Authored-By: ali@cal.com <alishahbaz7@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 10:13:33 +00:00
Eunjae LeeandDevin AI 1bb4b206c6 fix: default icon size to 16px in createIcon wrapper and fix download button alignment (#27924)
* fix: resolve insights page UI regressions for plus button size and download alignment

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: default icon size to 16px in createIcon wrapper

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 10:00:16 +00:00
Anik Dhabal Babu 6386b2ec95 fix: add e2e-spec pattern to CODEOWNERS test file exclusions (#27926)
* add e2e-spec pattern to CODEOWNERS

* Add pattern for test-suite files in CODEOWNERS
2026-02-13 15:18:32 +05:30
RomitandAnik Dhabal Babu 68abc63fe4 fix (#27902)
Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2026-02-13 09:46:37 +00:00
Syed Ali ShahbazandDevin AI bdeb4b1dc9 fix: use randomString() for booking uid in slots e2e tests to avoid unique constraint flake (#27916)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 06:18:52 -03:00
Devanshu SharmaandSahitya Chandra 1541730886 fix(app-store): preserve existing enabled state during seed (#27918)
* fix(app-store): preserve existing enabled state during seed

* Update seed-app-store.ts

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-02-13 08:34:06 +00:00
4c6af5659a fix: exclude test files from CODEOWNERS foundation approval (#27919)
* fix: exclude test files from CODEOWNERS foundation approval

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add *.test.* to CODEOWNERS test file exclusions

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add *.integration-test.* to CODEOWNERS test file exclusions

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 14:01:51 +05:30
Anik Dhabal Babu a9951df501 show invite link settings modal (#27917) 2026-02-13 04:13:17 +00:00
emrysal 68663231d8 chore: release v6.1.16
Post release / release (push) Canceled after 0s
Release Docker / Prepare Release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2026-02-12 23:27:31 +00:00
d3bbed01f6 feat: add signup watchlist review mode (#27912)
* feat: add signup watchlist review feature flag and handler logic

- Add 'signup-watchlist-review' global feature flag
- Add SIGNUP to WatchlistSource enum in Prisma schema
- When flag enabled, lock new signups and add email to watchlist
- Show 'account under review' message on signup page
- Add i18n strings for review UI
- Create seed migration for the feature flag

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* test: add isAccountUnderReview tests to fetchSignup test suite

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: address Cubic AI review feedback (confidence >= 9/10)

- Remove 'import process from node:process' in signup-view.tsx (P0 bug in 'use client' component)
- Move watchlist review check before checkoutSessionId early return in calcomSignupHandler (P1 premium bypass)
- Revert selfHostedHandler to original state (out of scope per user request)
- Add test mocks for FeaturesRepository and GlobalWatchlistRepository

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: remove node:process import from useFlags.ts (client-side file)

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* fix: remove !token condition from watchlist review check

Token is present in normal email-verified signups, so the !token
condition was incorrectly skipping watchlist review for verified users.

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* Apply suggestion from @cubic-dev-ai[bot]

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* refactor: move user lock to UserRepository.lockByEmail

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* refactor: use cached getFeatureRepository() instead of deprecated FeaturesRepository

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* refactor: remove user locking, keep only watchlist addition on signup review

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* feat: lock user on signup review, remove watchlist entry on unlock

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-02-12 23:14:31 +00:00
Volnei MunhozandDevin AI 9dfcb0d482 fix: include locale-prefixed paths in botid client-side protection (#27910)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-12 20:13:01 +00:00
Madhav KumarandAnik Dhabal Babu 240405f849 fix: Trimmed License Section in README (#27903)
* Pruned the 'License' section and Pushed it before 'Acknowledgement' to avoid confusion and Clarity

* Improves README file by pruning License Section and Aligning Properly

* Remove License section from README.md

---------

Co-authored-by: Anik Dhabal Babu <81948346+anikdhabal@users.noreply.github.com>
2026-02-12 17:46:20 +00:00
bc9a9c0c24 fix: Organised the OOO page (#27865)
* fixed text issue

* matched style of api keys page

* organised the out of office page

* Clean up unused imports in OutOfOfficeEntriesList

Removed unused imports from OutOfOfficeEntriesList.tsx

* fixed import issues

* remove unused imports

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Romit <romitgabani1.work@gmail.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-12 22:35:43 +05:30
Eunjae LeeandClaude Opus 4.6 f8abce44cb fix: update data-table hook imports missed in #27833 refactor (#27900)
* fix: update data-table hook imports after refactor (#27833)

The data-table hooks (useDataTable, useFilterValue) were moved from
@calcom/features/data-table to ~/data-table/hooks/ in #27833 but this
file was missed.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: update DataTableProvider import path in insights-wrong-routing-view

Another import missed in #27833 refactor — DataTableProvider moved from
@calcom/features/data-table/ to ~/data-table/.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 16:05:12 +00:00
Eunjae LeeandDevin AI 1368ffe55d refactor: move data-table hooks/contexts/provider from features to web modules (#27833)
* refactor: move data-table hooks/contexts/provider from features to web modules

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: update broken useColumnResizing import path in DataTable.tsx

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: update remaining broken import paths for moved hooks

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* docs: update GUIDE.md import paths and file references for moved modules

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-13 00:00:40 +09:00
Carina WollendorferandCarinaWolli 397bf3cc0c fix: use personal credits if no more team credits (#27518)
* use personal credits if team has no more credits

* clean up

* adjust comment

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2026-02-12 20:02:12 +05:30
sean-brydon 98ec38aeaa feat: add annual plans for teams/organizations (#27896)
* wip: add annual plan priceId support

* fix type errors

* type cast
2026-02-12 14:05:24 +00:00
d52e2d9fad feat: active user billing (#27867)
* factory and statergie

* chore: use correct method of DI

* feat: add onchagne

* add logic to HWM stat

* add webhook resolver methods to each statergy

* move seat tracking + webhooks over to own statergy

* Move to factory base approach

* move logic to correct class

* rename create -> createByTeamId

* fix: remove debug `true ||` overrides from IS_STRIPE_ENABLED and IS_TEAM_BILLING_ENABLED

Remove accidentally committed debug overrides that short-circuited
IS_STRIPE_ENABLED and IS_TEAM_BILLING_ENABLED to always be true,
bypassing Stripe credential checks. This would break self-hosted
instances without Stripe configured.

Identified by cubic (https://cubic.dev)

Co-Authored-By: unknown <>

* feat: active user billing

* add tests

* UI side for users on active billing

* use correct period of stripe sub

* feat: claude feedback

* fix: skip Stripe sync for canceled/expired subscriptions to prevent repeated API calls

Co-Authored-By: unknown <>

* feat: feedback

* feat: only render when active users mode is set

* fix type error

* fix: constants + feature flags

* fix: default to null in tests

* chore: use seats in test

* fix: use node:crypto protocol for Node.js builtin imports

Co-Authored-By: sean@cal.com <Sean@brydon.io>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-12 13:57:32 +00:00
bf348ee209 refactor: migrate Icon to component icons from @coss/ui/icons (#27458)
* feat: add @coss/ui/icons package and migrate static icon usages

Create a new icon system in @coss/ui/icons that wraps lucide-react icons
with controlled props (size and className only). Migrate 44 component
files from <Icon name="xxx" /> to <XxxIcon /> pattern.

This is Phase 1 of the icon migration, covering only static icon names.
Dynamic icon usages (e.g., name={variable}) are skipped for now.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 2)

Migrated 18 files from <Icon name="xxx" /> to <XxxIcon /> pattern:
- Event meta, insights, shell, user table bulk actions
- Webhooks, blocklist, form-builder, form components

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 3)

Migrated 7 files:
- CancelBooking, AddGuestsDialog, ChargeCardDialog
- ReassignDialog, RescheduleDialog
- Categories, Slider

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 4)

Migrated 6 files:
- Organizations: AboutOrganizationForm, PaymentStatusView, profile
- Workflows: CallDetailsSheet, SkeletonLoaderList, TimeTimeUnitInput

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate more static icons to @coss/ui/icons (batch 5)

Migrated 4 files:
- TwoFactorModalHeader
- App setups: alby, make, btcpayserver

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 6)

- confirmDialog.tsx: clock icon
- ics-feedcalendar/Setup.tsx: trash, plus icons
- hitpay/Setup.tsx: info icon
- paypal/Setup.tsx: circle-alert icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 7)

- webhook-edit-view.tsx: external-link icon
- webhook-new-view.tsx: external-link icon
- UserDropdown.tsx: chevron-down, user, settings, moon, map, circle-help, download, blocks, log-out icons
- TopNav.tsx: settings icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 8)

- EmailInviteForm.tsx: x icon
- InviteOptions.tsx: mail, upload, link icons
- SkeletonLoader.tsx: search, clock, user icons
- Embed.tsx: sun, arrow-left icons
- CalendarSwitch.tsx: arrow-left, rotate-cw icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 9)

- apps-view.tsx: search icon
- categories-view.tsx: arrow-left, arrow-right icons
- DatePicker.tsx: calendar icon
- EditLocationDialog.tsx: map-pin icon
- AppPage.tsx: circle-alert, book-open, external-link, mail, file, shield, flag icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 10)

- LicenseSelection.tsx: loader, check icons
- AppConnectionItem.tsx: circle-alert, arrow-right icons
- oauth-client-form/index.tsx: info icons (x2)
- auth/error/page.tsx: x icon
- troubleshoot/layout.tsx: loader icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 11)

- UpgradeTipWrapper.tsx: users, refresh-ccw, user-plus icons
- PbacOptInModal.tsx: shield-check, lock, users, shield icons
- AdvancedPermissionGroup.tsx: chevron-right, info icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 12)

- AdminAppsList.tsx: pencil icon
- AvailableTimes.tsx: calendar-x-2 icon
- BookingDetailsSheet.tsx: external-link (x2), repeat icons
- BookingCalendarContainer.tsx: chevron-left, chevron-right icons

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 13)

- videos-single-view.tsx: chevron-right icon
- TroubleshooterSidebar.tsx: arrow-left icon
- RuleBuilder.tsx: filter icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 14)

- FieldMappingBuilder.tsx: arrow-right, link icons
- IntegrationAttributeSyncCard.tsx: key icon
- onboarding-view.tsx: loader icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static icons to @coss/ui/icons (batch 15)

- team-profile-view.tsx: copy icon
- DateRangeFilter.tsx: check icon
- ColumnVisibilityButton.tsx: check icon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 16)

- EventWorkflowsTab.tsx: lock
- event-types-listing-view.tsx: search
- onboarding-migrate-members-browser-view.tsx: arrow-left, arrow-right, rotate-cw, lock, ellipsis-vertical, check, user-plus
- onboarding-migrate-teams-browser-view.tsx: arrow-left, arrow-right, rotate-cw, lock, ellipsis-vertical, check, arrow-right, users
- EventAvailabilityTab.tsx: globe, user
- onboarding-teams-browser-view.tsx: arrow-left, arrow-right, rotate-cw, lock, ellipsis-vertical, check, arrow-right, users
- FormBuilder.tsx: mail, phone, arrow-up, arrow-down
- AIEventController.tsx: info
- EventTeamAssignmentTab.tsx: x

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 17)

- EventAdvancedTab.tsx: pencil, info
- HostLocations.tsx: triangle-alert, loader
- EventTypeLayout.tsx: loader
- Locations.tsx: x, corner-down-right, check
- EditWeightsForAllTeamMembers.tsx: upload, search, info, chevron-down
- WorkflowPage.tsx: pencil

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 18)

- TestPhoneCallDialog.tsx: phone
- WorkflowListPage.tsx: link
- UsersTable.tsx: building, lock
- TeamList.tsx: building, paintbrush, chart-line, user-plus, users, pencil
- bookings-single-view.tsx: chevron-left, check, calendar, x, external-link

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate static Icon to @coss/ui/icons (batch 19)

- TeamsListing.tsx: users, refresh-ccw, user-plus, mail, video, eye-off, info
- ConnectionInfo.tsx: clipboard
- IntercomContactForm.tsx: message-circle, loader, send

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in teams components

- EventTypesList.tsx: check → CheckIcon
- MemberInvitationModal.tsx: user, users, building → UserIcon, UsersIcon, BuildingIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in workflow components

- ImportNumberDialog.tsx: info → InfoIcon
- VoiceSelector.tsx: user → UserIcon
- IncomingCallsTab.tsx: info, phone-incoming → InfoIcon, PhoneIncomingIcon
- PhoneNumberTab.tsx: loader, phone → LoaderIcon, PhoneIcon
- VoiceSelectionDialog.tsx: pause, play, user → PauseIcon, PlayIcon, UserIcon
- WebCallDialog.tsx: loader, phone, phone-off, triangle-alert, trash, message-circle → new icons (kept Icon import for dynamic mic icon)
- WorkflowDetailsPage.tsx: zap, arrow-right → ZapIcon, ArrowRightIcon
- AddActionDialog.tsx: info → InfoIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in WorkflowStepContainer

- info → InfoIcon (2 instances)
- phone → PhoneIcon (2 instances)
- circle-help → CircleHelpIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in data-table and org components

- attributes-list-view.tsx: tags → TagsIcon
- AddFilterButton.tsx: plus, eye-off → PlusIcon, EyeOffIcon
- BaseSelectFilterOptions.tsx: check → CheckIcon
- DataTable.tsx: arrow-up, arrow-down, check, chevrons-up-down, eye-off → new icons
- booking-dry-run-success-view.tsx: check → CheckIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: migrate static Icon to @coss/ui/icons in username and routing components

- UsernameTextfield.tsx: check → CheckIcon
- PremiumTextfield.tsx: check, external-link → CheckIcon, ExternalLinkIcon (kept Icon for star with fill prop)
- Header.tsx (routing-forms): pencil, menu, waypoints → PencilIcon, MenuIcon, WaypointsIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in routing-forms pages

Batch 25: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- Forms.tsx: file-text, shuffle, chart-bar, circle-check, mail, download → FileTextIcon, ShuffleIcon, ChartBarIcon, CircleCheckIcon, MailIcon, DownloadIcon
- FormEdit.tsx: chevron-down, menu → ChevronDownIcon, MenuIcon
- IncompleteBooking.tsx: globe → GlobeIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in UI package

Batch 26: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- ProgressToast.tsx: file-down, x → FileDownIcon, XIcon
- showToast.tsx: check, info, x → CheckIcon, InfoIcon, XIcon
- InfoBadge.tsx: info → InfoIcon
- MeetingTimeInTimezones.tsx: globe → GlobeIcon
- InputError.tsx: info → InfoIcon
- ConfirmationDialogContent.tsx: circle-alert, check → CircleAlertIcon, CheckIcon
- CalendarSwitch.tsx: arrow-left, rotate-cw → ArrowLeftIcon, RotateCwIcon
- ArrowButton.tsx: arrow-up, arrow-down → ArrowUpIcon, ArrowDownIcon
- FileUploader.tsx: upload → UploadIcon (kept Icon for dynamic)
- Checkbox.tsx: check → CheckIcon
- EditableHeading.tsx: pencil → PencilIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in UI and app-store packages

Batch 27: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- MultiEmail.tsx: x → XIcon (converted width to size)
- AppListCard.tsx: circle-alert → CircleAlertIcon
- SplitButton.tsx: chevron-down → ChevronDownIcon (kept Icon for dynamic)
- Calendar.tsx: chevron-left, chevron-right → ChevronLeftIcon, ChevronRightIcon
- AppDependencyComponent.tsx: check, circle-x, arrow-right → CheckIcon, CircleXIcon, ArrowRightIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in form input components

Batch 28: Migrate static Icon usages to @coss/ui/icons components.

Files changed:
- TextField.tsx: info → InfoIcon (kept Icon for x with onClick)
- Input.tsx: eye, eye-off, search → EyeIcon, EyeOffIcon, SearchIcon

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: use @coss/ui/src/icons in packages with legacy moduleResolution

Packages like packages/ui and packages/app-store use a legacy moduleResolution
setting that doesn't support subpath exports. This changes the import path from
@coss/ui/icons to @coss/ui/src/icons for these packages.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in UI form and editor components

Migrates static Icon usages:
- MultiOptionInput: x (2x), arrow-up, arrow-down
- components (select): check
- AddVariablesDropdown: chevron-down (3x)
- ToolbarPlugin: chevron-down

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: migrate Icon to component icons in settings and platform atoms

Migrates static Icon usages:
- SettingsLayoutAppDirClient: chevron-down (2x), chevron-right (2x), arrow-left
- platform/atoms dialog: x
- platform/atoms toast: x

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve @coss/ui/icons module resolution for legacy moduleResolution

Add typesVersions to @coss/ui package.json to help TypeScript resolve
subpath exports even with legacy moduleResolution: "node" setting.

Change imports from @coss/ui/src/icons to @coss/ui/icons to avoid
double-src path issue when Next.js applies import maps.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: localize 'Select field type' fallback label in FormEdit

Address Cubic AI review feedback (confidence 9/10) by using t() for
the hardcoded 'Select field type' string to ensure proper i18n support.

Co-Authored-By: unknown <>

* fix: add typesVersions wildcards for @coss/ui subpath imports

Add lib/*, components/*, and hooks/* to typesVersions to support
legacy moduleResolution with all package subpath patterns.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve missing Icon references in settings and workflows

- Add Icon import for dynamic icon usages in SettingsLayoutAppDirClient
- Replace static Icon usages with component icons (InfoIcon, PhoneIcon)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: resolve icon component type errors

- Add onClick prop support to IconProps
- Fix size prop type (use number instead of string)
- Rename local MailOpenIcon to MailOpenIconWrapper to avoid shadowing

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: add data-testid to icon components for test compatibility

- Add testId parameter to createIcon function
- Auto-generate data-testid for all icons (e.g., "check-icon", "search-icon")
- Remove outdated mock for @calcom/ui/components/icon in tests

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* Update package.json

* Update package.json

* fix: migrate Icon to CalendarDaysIcon in videos-single-view.tsx

Co-Authored-By: unknown <>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-12 14:30:27 +01:00
Hariom Balhara 635c1febb0 fix: Booking Drawer - text overlap in footer (#27897)
## What does this PR do?

Fixes footer text overlap in the Booking Details drawer where action buttons covered the last content items on smaller screens.

**Root cause:** `sm:-my-6` on `SheetFooter` applied both negative top and bottom margins. The negative top margin pulled the footer up into the body content area, causing the overlap.

**Fix:**
- Removed `-mb-4` and `sm:-my-6` from `SheetFooter`, keeping only horizontal negative margins (`-mx-4` / `sm:-mx-6`) for edge-to-edge stretch
- Added `pb-0` to `SheetContent` to remove bottom padding so the footer sits flush at the bottom on all breakpoints

<img width="1098" height="1362" alt="image" src="https://github.com/user-attachments/assets/0418df56-a432-4edf-8e5b-664a5e8c18ac" />

- Fixes #XXXX (GitHub issue number)
- Fixes CAL-XXXX (Linear issue number - should be visible at the bottom of the GitHub issue description)

## Visual Demo (For contributors especially)

#### Image Demo (if applicable):

See screenshot above showing the overlap bug. The footer actions ("..." button) overlap with the last booking history entry.

## Mandatory Tasks (DO NOT REMOVE)

- [ ] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [ ] I have updated the developer docs in /docs if this PR makes changes that would require a [documentation change](https://cal.com/docs). If N/A, write N/A here and check the checkbox.
- [ ] I confirm automated tests are in place that prove my fix is effective or that my feature works.

## How should this be tested?

1. Open any booking in the bookings list to open the details drawer
2. Scroll to the bottom of the drawer content
3. Verify the footer actions (buttons, dropdown) do not overlap with the last content item
4. Test on both mobile and desktop viewport sizes — footer should sit flush at the bottom with no extra gap on either

## Human Review Checklist

- [ ] Verify footer appearance on **mobile** (below `sm` breakpoint) — no gap below footer, no overlap with content
- [ ] Verify footer appearance on **desktop** (`sm+` breakpoint) — same checks
- [ ] Confirm the footer still stretches edge-to-edge horizontally on both breakpoints

## Checklist

- I haven't read the [contributing guide](https://github.com/calcom/cal.com/blob/main/CONTRIBUTING.md)
- My code doesn't follow the style guidelines of this project
- I haven't commented my code, particularly in hard-to-understand areas
- I haven't checked if my changes generate no new warnings
- My PR is too large (>500 lines or >10 files) and should be split into smaller PRs

---

Link to Devin run: https://app.devin.ai/sessions/b9d130b8a7a54f039b90b53921b19c78
Requested by: @hariombalhara
2026-02-12 18:50:33 +05:30
emrysal 8beb629b07 chore: release v6.1.15
Post release / release (push) Canceled after 0s
Release Docker / Prepare Release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2026-02-12 13:09:31 +00:00
7cfb053026 feat: add wrong routing tab under Insights for reviewing assignment reports (#27423)
* Add DB table for wrong assignment reports

* When report is submitted write to the db

* Prevent duplicate reportings

* test: add migration and tests for WrongAssignmentReport table

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add unique constraint on bookingUid and booking access check for hasWrongAssignmentReport

- Add @unique constraint on bookingUid in WrongAssignmentReport model to prevent duplicate reports at DB level
- Add booking ownership check using BookingAccessService in hasWrongAssignmentReport endpoint
- Refactor hasWrongAssignmentReport into separate handler and schema files

Addresses Cubic AI review feedback on PR #27405

Co-Authored-By: unknown <>

* feat: add routingFormId to WrongAssignmentReport and fix Select clearing

- Add routingFormId field to WrongAssignmentReport model in schema.prisma
- Add relation to App_RoutingForms_Form with SetNull on delete
- Update WrongAssignmentReportRepository.createReport to accept routingFormId
- Update BookingRepository.findByUidIncludeEventTypeAndTeamAndAssignmentReason to include routedFromRoutingFormReponse
- Extract routingFormId from booking in reportWrongAssignment handler
- Fix Select clearing issue: handle null case when user clears team member selection
- Update tests to include routingFormId field

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* chore: add migration for routingFormId in WrongAssignmentReport

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add wrong assignment reports dashboard under routing tab

- Add reviewedById and reviewedAt fields to WrongAssignmentReport model
- Add repository methods for listing reports by status and updating status
- Create tRPC endpoints for fetching reports and updating status
- Create dashboard UI with pending/reviewed tabs showing routing form name
- Add translation keys for dashboard UI
- Integrate dashboard into routing insights page

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: move hooks before early return and fix indentation

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: address Udit's review comments

- hasWrongAssignmentReport: throw UNAUTHORIZED error instead of returning false
- reportWrongAssignment: add try-catch for Prisma P2002 unique constraint error
- WrongAssignmentReport: add Team relation to teamId field
- WrongAssignmentReportRepository: use findUnique instead of findFirst
- reportWrongAssignment: use i18n for error messages

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: revert hasWrongAssignmentReport to return false when user lacks access

Per PR checklist, hasWrongAssignmentReport should return { hasReport: false }
when user lacks access to booking, not throw an error. This allows the UI
to gracefully treat 'no access' as 'no report exists'.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: update mocks for findUnique and i18n in unit tests

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: throw UNAUTHORIZED in hasWrongAssignmentReport and squash migrations

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: move wrong assignment reports to its own tab under Insights

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Use data table for wrong reports

* Add option to view routing trace

* feat: add view routing form submission action to wrong assignment reports

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add RoutingFormResponseSheet component for viewing form submissions

- Create slide-out sheet to display routing form responses
- Map option IDs to display labels for select/multiselect fields
- Handle both legacy and modern option formats
- Add i18n strings: form_submission, no_responses_found

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: improve wrong assignment reports UX

- Integrate RoutingFormResponseSheet as slide-out panel instead of new tab
- Fix dropdown padding by using StartIcon prop instead of manual Icon
- Allow direct status changes for reviewed reports (no need to reopen first)
- Remove unused Icon import

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: change User relation onDelete from Cascade to SetNull in WrongAssignmentReport

Address Hariom's review feedback:
- Changed reportedById from Int to Int? (nullable)
- Changed reportedBy relation from onDelete: Cascade to onDelete: SetNull
- Updated migration SQL to reflect these changes

This preserves wrong assignment reports even when the reporting user is deleted,
as the data is still useful for analysis.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add missing i18n strings for wrong assignment reports dashboard

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: move form response display value resolution server-side

Replace client-side option ID to label resolution in
RoutingFormResponseSheet with a new lean tRPC endpoint
(getFormResponseDisplay) that resolves values server-side using
the existing getHumanReadableFieldResponseValue utility. This
enforces DTO boundaries by returning a clean pre-resolved payload
instead of leaking internal option format details to the client.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add report wrong assignment button to routing trace sheet

Wire up the WrongAssignmentDialog from the routing trace sheet header
so users can flag wrong assignments directly while viewing the trace.
The report button is disabled with a tooltip when a report already
exists.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: reuse existing WrongAssignmentDialog from parent

Replace the duplicate WrongAssignmentDialog in RoutingTraceSheet with
a callback to the existing instance in BookingActionsDropdown. This
reduces the prop surface from a 6-field reportContext object to an
onReport callback and hasExistingReport boolean.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: use repository instead of direct Prisma in getFormResponseDisplay

Replace direct Prisma query with PrismaRoutingFormResponseRepository's
findByIdIncludeForm method. Extend the method to also select form name,
description, userId, and teamId needed for display and auth checks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: replace direct Prisma calls with repository methods

Use MembershipRepository.hasMembership() for auth checks and
TeamRepository.findAllByParentId() for child team queries instead
of direct Prisma calls. Replace direct user query with
UserRepository.getTimeZoneAndDefaultScheduleId(). Remove unused
seed script.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: use PBAC services for wrong assignment report auth

Replace manual MembershipRepository.hasMembership() checks with
PBAC-aware permission checking. getWrongAssignmentReports uses
createTeamPbacProcedure middleware since teamId is in input.
updateWrongAssignmentReportStatus uses PermissionCheckService
directly since teamId is discovered from the report entity.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: resolve type errors in RoutingFormResponseSheet and wrong-routing view

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add seed script for wrong assignment reports test data

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Revert "feat: add seed script for wrong assignment reports test data"

This reverts commit 0bd60e9661858a59aab1573d14d57d81733b7991.

* Only update reviewed fields when not pending

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor: wrap handleStatusChange in useCallback to fix useMemo recalculation

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Fix routing sheet UI

* fix: use appropriate error message in getFormResponseDisplay handler

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: extract WrongAssignmentReportService from tRPC handlers

Move business logic (booking lookup, duplicate check, report creation,
webhook dispatch, org-level team resolution) into a dedicated service
in packages/features. Handlers become thin controllers that only handle
auth checks and delegate to the service.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: restrict report status updates to admin/owner roles

Remove MembershipRole.MEMBER from fallbackRoles in
updateWrongAssignmentReportStatus permission check. Updating report
status is an administrative action that should be limited to team
admins and owners.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: localize hard-coded success message in WrongAssignmentReportService

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: rename reviewed tab to handled and add missing translations

Rename the "Reviewed" tab to "Handled" since it groups three distinct
statuses (Reviewed, Resolved, Dismissed). Also add missing translation
keys for "resolved" and "dismissed" status badges.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* merge: resolve conflicts with main branch

Merge main into devin/1769747741-wrong-assignment-dashboard, resolving conflicts in:
- BookingActionsDropdown.tsx: use main's booking prop with PR's fragment structure
- reportWrongAssignment.handler.ts: keep PR's service-based approach
- reportWrongAssignment.handler.test.ts: use main's class-based mocks with PR's additions
- WrongAssignmentReportService.ts: align with main's repo method and field names

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Add guard when accessing assignmentReasonSortedByCreatedAt

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: address Cubic AI review feedback - select projection and useLocale refactor

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: remove stale TRPCError assertion in test (service throws ErrorWithCode)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: remove unused findByTeamIdAndStatus and findByTeamIdAndStatuses methods

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* perf: add composite index on WrongAssignmentReport and narrow findByIdIncludeForm select

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

* perf: use lightweight findTeamIdById in update-status handler instead of findById

Co-Authored-By: alex@cal.com <me@alexvanandel.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: hariom@cal.com <hariombalhara@gmail.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: alex@cal.com <me@alexvanandel.com>
2026-02-12 13:02:33 +00:00
Hariom Balhara 50c5423ba7 fix: support underscores in workflow template variables with backward compatibility (#27571)
## What does this PR do?

Fixes an issue where underscores in form field identifiers were being stripped when converting to workflow template variables. According to the documentation, users should be able to use variables like `{COMPANY_NAME}` or `{MONTHLY_INFRASTRUCTURE_SPEND}`, but the regex in `formatIdentifierToVariable` was removing underscores, causing these variables to not match.

**The problem:**
- Form field identifier: `Company_Name` or `Monthly_Infrastructure_Spend`
- Expected variable: `{COMPANY_NAME}` or `{MONTHLY_INFRASTRUCTURE_SPEND}`
- Actual variable (before fix): `{COMPANYNAME}` or `{MONTHLYINFRASTRUCTURESPEND}`

**The fix:**
- Updated the regex from `[^a-zA-Z0-9 ]` to `[^a-zA-Z0-9_ ]` to preserve underscores in `formatIdentifierToVariable`
- Added a private `formatIdentifierToVariableLegacy` function that maintains the old behavior (strips underscores)
- Added `getVariableFormats` helper that returns both current and legacy formats for backward compatibility
- Added `convertResponsesToVariableFormats` helper in `executeAIPhoneCall.ts` to convert form responses to both variable formats
- Updated `customTemplate.ts` matching logic to support both variable formats
- Updated `executeAIPhoneCall.ts` to include both variable formats when building dynamic variables

This ensures existing templates using `{COMPANYNAME}` continue to work while new templates can use the documented `{COMPANY_NAME}` format.

## Mandatory Tasks (DO NOT REMOVE)

- [x] I have self-reviewed the code (A decent size PR without self-review might be rejected).
- [x] I have updated the developer docs in /docs if this PR makes changes that would require a documentation change. N/A - no docs changes needed.
- [x] I confirm automated tests are in place that prove my fix is effective or that my feature works.

## How should this be tested?

1. Create a routing form with a field identifier containing underscores (e.g., `Company_Name`)
2. Create a workflow with a template using `{COMPANY_NAME}` (with underscore)
3. Submit the form and verify the variable is replaced correctly
4. Also test with `{COMPANYNAME}` (without underscore) to verify backward compatibility

**Automated tests added:**
- `customTemplate.test.ts` - 15 tests covering `formatIdentifierToVariable`, `getVariableFormats`, and template variable replacement
- `executeAIPhoneCall.test.ts` - 6 tests covering `convertResponsesToVariableFormats` function for form responses

## Human Review Checklist

- [ ] Verify the regex change `[^a-zA-Z0-9_ ]` correctly preserves underscores
- [ ] Verify backward compatibility: both `{COMPANY_NAME}` and `{COMPANYNAME}` should work for the same form field
- [ ] Verify `convertResponsesToVariableFormats` correctly generates both variable formats
- [ ] Review test coverage for edge cases (empty responses, undefined values)

---

Link to Devin run: https://app.devin.ai/sessions/9d5d90178714493086d94691865c3e07
Requested by: @hariombalhara
<!-- devin-review-badge-begin -->

---

<a href="https://app.devin.ai/review/calcom/cal.com/pull/27571">
  <picture>
    <source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-open-in-devin-review-dark.svg?v=1">
    <img src="https://static.devin.ai/assets/gh-open-in-devin-review-light.svg?v=1" alt="Open with Devin">
  </picture>
</a>
<!-- devin-review-badge-end -->
2026-02-12 17:21:42 +05:30
Anirban Singha 7716f8c0a1 feat: add list formatting options to profile and event description editor (#27838) 2026-02-12 10:42:03 +00:00
8a3944f987 chore: Remove /api/ routes from proxy (#27883)
* chore: Remove /api/ routes from proxy

* Update apps/web/proxy.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* Add tests: apps/web/proxy.test.ts

Generated by Paragon from proposal for PR #27883

* Update proxy.test.ts

* fix: update proxy tests to account for /api/auth/signup in matcher

Co-Authored-By: unknown <>

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-12 07:33:47 -03:00
Dhairyashil Shinde be0b707296 style: take feedback dialog little right (#27892) 2026-02-12 14:32:36 +05:30
fad64a012a fix(form-builder): correct value of selection box behavior in Edit of new Added Question dialog (#27890)
* fix/SelectionBox Issue

* comment removed

* remove empty lines

---------

Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
Co-authored-by: Romit <romitgabani1.work@gmail.com>
2026-02-12 13:36:05 +05:30
Eunjae LeeandDevin AI 14563f664e feat: re-render bookings page after feature opt-in without full refresh (#27873)
* feat: re-render bookings page after feature opt-in without full refresh

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: make onOptInSuccess a required prop

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-12 10:41:40 +05:30
c7e66a3aa9 fix: maintain uid parameter in BookingDetailsSheet URL (#27872)
* fix: maintain uid parameter in BookingDetailsSheet URL

Move the isSyncedFromUrlToStoreRef guard from the effect level to inside
the Zustand subscription callback. This ensures the Store→URL subscription
is always created while still preventing premature URL overwrites during
URL→Store sync.

Also adds an E2E test verifying the uid parameter appears in the URL
after clicking a booking item in the v3 bookings view.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* Update apps/web/playwright/bookings-list.e2e.ts

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: clean up bookings-v3 feature flag after E2E test

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-02-12 10:39:08 +05:30
Pedro Castro 0d55939d13 chore(deps): resolve fast-xml-parser to 5.3.4 for @lingo.dev/_compiler (#27887) 2026-02-12 01:26:59 +00:00
06bb994145 fix: Improve wrong assignment report (#27162)
* Pass already fetched booking

* Fetch the assignment reason

* Update tests

* Label as first assignment reason

* Pass single booking object

* Remove unused repository method

* Only pass bookingUid to handler

* Rename booking `assignmentReason` to `assignmentReasonSortedByCreatedAt`

* fix: use renamed assignmentReasonSortedByCreatedAt property

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Remove take statement

* fix: address Udit's review comments

- Restore BookingAccessService for access control checks
- Rename repository method from findByUidForWrongAssignmentReport to findByUidIncludeUserAndEventTypeTeamAndAttendeesAndAssignmentReason

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: update tests to use BookingAccessService mock

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use latest assignment reason in BookingDetailsSheet for consistency

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-11 13:12:21 -05:00
Udit Takkar b185cd231b feat: login overlay re design (#27800) 2026-02-11 15:12:10 +00:00
Anik Dhabal Babu 4c804cdb00 fix flakes (#27849) 2026-02-11 14:51:34 +00:00
Eunjae LeeandClaude Opus 4.6 98b6d63164 refactor: apply biome formatting to packages/features (#27844)
* refactor: apply biome formatting to packages/features (batch 1 - small subdirs)

Format small subdirectories in packages/features: di, flags, holidays, oauth,
settings, users, assignment-reason, selectedCalendar, hashedLink, host, form,
form-builder, availability, data-table, pbac, schedules, troubleshooter,
eventtypes, calendar-subscription, and root-level files.

Also includes straggler apps/web BookEventForm.tsx.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: apply biome formatting to packages/features (batch 2 - medium subdirs)

Format medium subdirectories in packages/features: auth, credentials,
calendars, routing-forms, routing-trace, attributes, watchlist, calAIPhone,
tasker, and webhooks.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: apply biome formatting to packages/features (batch 3 - bookings + insights)

Format bookings and insights subdirectories in packages/features.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: apply biome formatting to packages/features (batch 4 - ee)

Format packages/features/ee subdirectory covering billing, workflows,
organizations, teams, managed-event-types, round-robin, dsync,
integration-attribute-sync, and payments.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: apply biome formatting to packages/features (batch 5 - booking-audit part 1)

Format booking-audit di, actions, common, dto, repository, and types
subdirectories in packages/features/booking-audit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: apply biome formatting to packages/features (batch 6 - booking-audit part 2)

Format booking-audit service subdirectory in packages/features/booking-audit.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-11 15:47:14 +01:00
Keith WilliamsandDevin AI bc8ebb9213 perf: use UNION ALL with DISTINCT for bookings query optimization (#27841)
* perf: use UNION ALL with DISTINCT for bookings query optimization

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: add unionAll and distinct to kysely test mocks

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: add integration tests for getBookings query

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: add totalCount deduplication test for multi-branch union scenario

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: fix totalCount assertion to be exact instead of gte

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Apply suggestion from @keithwillcode

* perf: restore COUNT(DISTINCT id) for totalCount query

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Add tests: packages/trpc/server/routers/viewer/bookings/get.handler.integration-test.ts

Generated by Paragon from proposal for PR #27841

* Add tests: packages/trpc/server/routers/viewer/bookings/get.handler.test.ts

Generated by Paragon from proposal for PR #27841

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-11 11:33:11 -03:00
6089f47d24 feat: add fallback action options to routing form fallback section (#27449)
* feat: add no users found fallback action for routing forms

- Add NoUsersFoundFallbackActionType enum with CustomPageMessage and ExternalRedirectUrl options
- Add noUsersFoundFallbackAction field to zodNonRouterRoute schema
- Add NoUsersFoundFallback UI component in RouteBuilder for configuring fallback action
- Update handleResponse to return noUsersFoundFallbackAction when no team members match
- Add i18n translation keys for new UI strings

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: change fallback to use same action options as main route

- Replace noUsersFoundFallbackAction with fallbackAction that has same structure as main action
- Add action dropdown and input fields to fallback attributes query builder section
- Support Event redirect, External URL, and Custom page options in fallback
- Remove separate NoUsersFoundFallback toggle component
- Update handleResponse to return fallbackAction

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: ensure fallbackAction type is always defined in onChange handlers

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add guards for route.fallbackAction in onChange handlers

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: only return fallbackAction when no users are found

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: restructure fallback section to mirror main route structure

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: ensure backwards compatibility for existing routes with fallbackAttributesQueryValue

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: initialize fallbackAction with main event type for backwards compatibility

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: include fallbackAction in getRoutesToSave to persist changes

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use fallbackAction in getRoutedUrl when no team members found

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use i18n for fallback label and add tests for fallback action

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: do not trigger fallback action when CRM contact owner is found

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: prioritize fallbackAction over fallbackAttributesQueryValue

When a route has a fallbackAction configured, skip the
fallbackAttributesQueryValue to ensure the fallbackAction is triggered
when no team members are found. This maintains backwards compatibility
by only using fallbackAttributesQueryValue when fallbackAction is not set.

Also treats teamMemberIdsMatchingAttributeLogic being null (routing couldn't
run, e.g., missing orgId) the same as an empty array for the purpose of
triggering the fallbackAction.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: extract RouteActionSelector shared component for action selection UI

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add i18n string for default custom page message

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* feat: add webhook trigger when routing form fallback route is hit

- Add ROUTING_FORM_FALLBACK_HIT to WebhookTriggerEvents enum in Prisma schema
- Add new trigger to routing-forms webhook triggers in constants
- Add translation string for the new webhook trigger
- Implement triggerFallbackWebhook function in formSubmissionUtils.ts
- Call webhook trigger from handleResponse.ts when fallback action is used

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: remove webhook object from error log to avoid exposing secrets

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* revert: remove webhook trigger changes (to be moved to separate PR)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: only show fallback query builder when fallbackAction is explicitly set

The fallback attributes query builder was being shown for new routes
when fallbackAction was not set, causing an extra 'Add rule' button
to appear. This broke e2e tests that relied on the button index.

Now the fallback query builder is only shown when fallbackAction is
explicitly set to EventTypeRedirectUrl, which happens after the route
is saved and reloaded (via auto-initialization in useRoutes).

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use data-testid for attribute query builder selectors in e2e tests

- Add data-testid='attributes-query-builder' to the main attributes query builder div
- Update addAttributeRoutingRule and addAttributeRoutingRuleWithOperator to use the data-testid selector instead of nth() indices
- This makes the tests more robust and independent of DOM structure changes

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: initialize fallbackAction for new routes in useCreateRoute hook

- New routes created via useCreateRoute now initialize fallbackAction
- This ensures new routes have a valid fallbackAction when saved
- Matches the initialization logic for existing routes in useRoutes

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: initialize fallbackAction at save time when action is EventTypeRedirectUrl

- When saving routes, if fallbackAction is undefined but action is EventTypeRedirectUrl,
  initialize fallbackAction from the main action
- This handles the case where user creates a new route and changes action to an event type
- Fixes e2e test failures where form save was failing due to undefined fallbackAction

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: initialize fallbackAction when main action changes to EventTypeRedirectUrl

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: only show fallback section when main action has valid event type selected

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: check for valid fallbackAction event type before preserving existing value

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* Give more structure to main and fallback routes

* Update comment

* Rename fallbackAttributesQueryBuilder to matchingMembersFallbackRoute

* Display custom event redirect input

* fix: address Cubic AI review feedback for routing form fallback

- Simplify getFallbackAction logic to use checkedFallback flag instead of
  manually parsing attributesQueryValue (confidence 9/10)
- Add i18n translation for 'And connect with specific team members' string
  using t('connect_with_specific_team_members') (confidence 9/10)

Co-Authored-By: unknown <>

* fix: update getFallbackAction to use checkedFallback and handle missing orgId case

- Use checkedFallback flag as primary indicator for triggering fallback action
- Also handle edge case where attribute routing was configured but couldn't run
  due to missing orgId (teamMemberIdsMatchingAttributeLogic is null)
- Update test to mock checkedFallback: true when expecting fallback action

Co-Authored-By: unknown <>

* Address UI comment

* fix: Use fallbackAttributesQueryValue when fallback action is event redirect

Only use fallbackAttributesQueryValue when:
1. fallbackAction is EventTypeRedirectUrl (attribute routing applies)
2. fallbackAction is not set (backwards compatibility)

Skip it for CustomPageMessage and ExternalRedirectUrl fallback actions
since attribute routing doesn't apply to those action types.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: correct JSX syntax error in matchingMembersFallbackRoute

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: extract getCustomSlug helper to deduplicate custom event type slug logic

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: only show fallback attribute filtering for teams under orgs

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: show fallback action for all team forms, gate attribute filtering on isOrganization

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2026-02-11 09:15:16 -05:00
saptarshi-bose f6fa24de2b adjusted zoho Token expiry time to miliseconds. (#27855)
The Date.now() method returns time in epoch miliseconds, adding 60 * 60 = 3.6seconds leads to a bug that results in expiring the access token in 3.6 seconds, although it been valid. It creates unnecessary api calls to the zoho servers before most the api calls.
2026-02-11 12:49:44 +00:00
Shrey-SutariyaandRomit b75000ea7b feat(form-builder): format field labels with spaces (#27858)
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-11 11:37:45 +00:00
Benny Joo dc7b9d91ae chore: add agent rules to prevent circular dependencies between packages (#27860) 2026-02-11 12:00:57 +01:00
36713fc12e feat: add UTM parameter data to insights bookings CSV download (#27854)
* feat: add UTM parameter data to insights bookings CSV download

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* test: add UTM data tests and update snapshots for csvDataTransformer

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* fix: use Tracking relation for UTM data instead of flat fields on Booking

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-11 15:28:54 +05:30
Anik Dhabal Babu 285f6d54a3 fix: unable to add and remove org banner (#27848) 2026-02-11 06:58:20 +00:00
Peer Richelsen 1e0cf3d0f6 feat: caretta.so app (#27840)
* new caretta.so app

* added logo and screenshots

* nit
2026-02-11 06:45:34 +00:00
681d191537 fix: ensure metadata key is always present in BOOKING_CREATED webhook payload (#27300)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: ali@cal.com <ali@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2026-02-11 06:05:51 +00:00
Anik Dhabal BabuandDevin AI 269ed87db4 fix: use unique UIDs in seated slots E2E tests to prevent flaky uid collisions (#27847)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-11 00:55:38 -03:00
Madhav KumarandVolnei Munhoz 0191f54519 Populated Contributing Section with a welcoming summary (#27830)
Co-authored-by: Volnei Munhoz <volnei@cal.com>
2026-02-11 03:02:54 +00:00
Everton Resende dc3e681e01 fix: hide cancel/reschedule links in emails when disabled (#27637)
When disableCancelling or disableRescheduling is enabled on an event type,
the confirmation email still showed non-functional cancel/reschedule links.

The ManageLink email component already had correct conditional logic to
hide these links, but two flows constructed the CalendarEvent manually
without including the flags: the booking confirmation handler and the
payment booking flow. This caused the flags to be undefined, which
ManageLink interpreted as enabled.

Added disableCancelling and disableRescheduling to the Prisma select and
CalendarEvent object in both confirm.handler.ts and getBooking.ts.

Closes #22906
2026-02-10 18:57:54 -03:00
Romit 30bba3da15 fix (#27478) 2026-02-10 18:56:45 -03:00
Udit Takkar cfa0783ebc feat: add claude specs (#26852)
* feat: claude templates

* refactor: new file

* feat: symlink
2026-02-10 19:06:31 +00:00
81e4241f85 refactor: apply biome formatting to apps/web (#27692)
* refactor: apply biome formatting to apps/web (batch 1)

Formats apps/web non-modules directories:
- apps/web/app
- apps/web/lib
- apps/web/pages
- apps/web/styles
- apps/web/server
- apps/web/test
- Root-level .ts and .mjs files

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to apps/web/modules (batch 2)

Formats smaller apps/web/modules directories:
- onboarding, data-table, users, apps, auth
- integration-attribute-sync, shell, availability
- feature-flags, team, webhooks, getting-started
- feature-opt-in, troubleshooter, schedules, notifications
- signup-view.tsx

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to apps/web/modules (batch 3)

Formats medium apps/web/modules directories:
- bookings
- event-types
- insights
- embed

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to apps/web/modules/ee (batch 4)

Formats apps/web/modules/ee directory.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to apps/web (batch 5)

Formats remaining apps/web directories:
- apps/web/modules/settings
- apps/web/modules/booking-audit
- apps/web/playwright

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to apps/web/components (batch 6)

Formats remaining apps/web/components files.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to new apps/web files from main

Formats newly added/modified files from main merge:
- WorkflowStepContainer.tsx (resolved merge conflicts)
- Newly moved files (blocklist, form-builder, schedules, etc.)
- Other files modified in main

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: apply biome formatting to new apps/web files from main

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 23:25:24 +05:30
f4abbb2de1 feat: refactor billing to strategy implemention (#27828)
* factory and statergie

* chore: use correct method of DI

* feat: add onchagne

* add logic to HWM stat

* add webhook resolver methods to each statergy

* move seat tracking + webhooks over to own statergy

* Move to factory base approach

* move logic to correct class

* rename create -> createByTeamId

* fix: remove debug `true ||` overrides from IS_STRIPE_ENABLED and IS_TEAM_BILLING_ENABLED

Remove accidentally committed debug overrides that short-circuited
IS_STRIPE_ENABLED and IS_TEAM_BILLING_ENABLED to always be true,
bypassing Stripe credential checks. This would break self-hosted
instances without Stripe configured.

Identified by cubic (https://cubic.dev)

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 13:11:36 -03:00
3908cda372 perf: optimize getBusyTimesForLimitChecks with batched parallel queries (#27399)
* perf: optimize getBusyTimesForLimitChecks with batched parallel queries and raw SQL

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* test: add unit tests for getBusyTimesForLimitChecks batched query optimization

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* refactor: use Prisma findMany instead of raw SQL for better testability

The batching (50 user chunks) and parallel execution (Promise.all) provide
the main performance optimization. Using findMany instead of $queryRaw
maintains the same performance characteristics while being compatible
with prismock for testing.

Co-Authored-By: udit@cal.com <udit222001@gmail.com>

* fix: type error

* refactor: add integration test

* chore: remove log

* chore: remove log

* fix: avoid logging PII (userId) in busyTimes debug log

Replace JSON.stringify(busyTimes) with count to avoid exposing userId
in logs. Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* chore: undo

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 15:56:30 +00:00
Rajiv Sahal db76980644 fix: API v2 @GetWebhook() decorator doesn't generate OpenAPI path (#27612)
* fix: openapi spec for GetWebhook decorator

* fix: openapi spec
2026-02-10 11:56:55 -03:00
sean-brydon d8e6ecc7a0 fix: add i18n + migration (#27836) 2026-02-10 14:44:19 +00:00
16eb96e27d fix: update booking page terms text to use APP_NAME instead of "our" (#27834)
* fix: update booking page terms text to use APP_NAME instead of 'our'

Co-Authored-By: carina@cal.com <c.wollendorfer@me.com>

* remove changes for platform booker

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: CarinaWolli <wollencarina@gmail.com>
2026-02-10 14:41:00 +00:00
Pedro Castro 83c42cfb2b chore: resolve @modelcontextprotocol/sdk to 1.26.0 (#27640) 2026-02-10 22:28:21 +09:00
Udit TakkarandHariom Balhara 589260a7c7 fix: host location option (#27807)
Post release / release (push) Canceled after 0s
Release Docker / Prepare Release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
Co-authored-by: Hariom Balhara <1780212+hariombalhara@users.noreply.github.com>
2026-02-10 13:21:57 +00:00
emrysal ff076d2394 chore: release v6.1.14 2026-02-10 13:18:45 +00:00
Alex van Andel ee1748dbee Revert "fix: prevent layout shift in sticky navbar (#27256)"
This reverts commit 38492d5839.
2026-02-10 13:09:04 +00:00
Alex van Andel 0a68a189f2 Revert "fixed header (#27794)"
This reverts commit 6f6c27b47d.
2026-02-10 13:09:01 +00:00
Alex van Andel abbc8bbb7b Revert "fix: availability page UI (#27825)"
This reverts commit 267686704d.
2026-02-10 13:05:50 +00:00
Hariom Balhara 11f336811b feat: add non-interactive mode to app-store CLI (#27831) 2026-02-10 13:59:00 +01:00
Keith Williams 3fd922664f chore: Update CODEOWNERS for Shell.tsx (#27835) 2026-02-10 18:18:25 +05:30
ae31e05bec refactor: decouple @calcom/features from @calcom/trpc/server [2] (#27821)
* inviteMemberUtils in featuers

* update imports

* wip

* wip

* fix: remove PII from log statements in inviteMemberUtils

- Remove email (usernameOrEmail) from error log in sendSignupToOrganizationEmail
- Replace full user object with userId in debug log in sendExistingUserTeamInviteEmails

Co-Authored-By: unknown <>

* revert: restore original code for pure relocation (no formatting/logic changes)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* fix: update test mocks to use new import path for inviteMemberUtils

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* revert: restore original formatting in proration test and handleGroupEvents

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 09:29:32 -03:00
Benny JooandDevin AI 431fbe44fc refactor: decouple @calcom/features from @calcom/trpc/server (#27751)
* make GetPublicEventInput

* space

* mv feature flags router to trpc

* remove trpc imports

* wip

* mv OrgMembershipLookup to features

* fix

* fix

* update

* fix

* revert formatting-only changes to improve PR reviewability

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 09:28:37 -03:00
c0504993a6 feat: Write wrong assignment reports to the database (#27405)
* Add DB table for wrong assignment reports

* When report is submitted write to the db

* Prevent duplicate reportings

* test: add migration and tests for WrongAssignmentReport table

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: add unique constraint on bookingUid and booking access check for hasWrongAssignmentReport

- Add @unique constraint on bookingUid in WrongAssignmentReport model to prevent duplicate reports at DB level
- Add booking ownership check using BookingAccessService in hasWrongAssignmentReport endpoint
- Refactor hasWrongAssignmentReport into separate handler and schema files

Addresses Cubic AI review feedback on PR #27405

Co-Authored-By: unknown <>

* feat: add routingFormId to WrongAssignmentReport and fix Select clearing

- Add routingFormId field to WrongAssignmentReport model in schema.prisma
- Add relation to App_RoutingForms_Form with SetNull on delete
- Update WrongAssignmentReportRepository.createReport to accept routingFormId
- Update BookingRepository.findByUidIncludeEventTypeAndTeamAndAssignmentReason to include routedFromRoutingFormReponse
- Extract routingFormId from booking in reportWrongAssignment handler
- Fix Select clearing issue: handle null case when user clears team member selection
- Update tests to include routingFormId field

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* chore: add migration for routingFormId in WrongAssignmentReport

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: address Udit's review comments

- hasWrongAssignmentReport: throw UNAUTHORIZED error instead of returning false
- reportWrongAssignment: add try-catch for Prisma P2002 unique constraint error
- WrongAssignmentReport: add Team relation to teamId field
- WrongAssignmentReportRepository: use findUnique instead of findFirst
- reportWrongAssignment: use i18n for error messages

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: revert hasWrongAssignmentReport to return false when user lacks access

Per PR checklist, hasWrongAssignmentReport should return { hasReport: false }
when user lacks access to booking, not throw an error. This allows the UI
to gracefully treat 'no access' as 'no report exists'.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: update mocks for findUnique and i18n in unit tests

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: throw UNAUTHORIZED in hasWrongAssignmentReport and squash migrations

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: change User relation onDelete from Cascade to SetNull in WrongAssignmentReport

Address Hariom's review feedback:
- Changed reportedById from Int to Int? (nullable)
- Changed reportedBy relation from onDelete: Cascade to onDelete: SetNull
- Updated migration SQL to reflect these changes

This preserves wrong assignment reports even when the reporting user is deleted,
as the data is still useful for analysis.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 08:00:01 -03:00
c3a8301b0c fix: hide feature opt-in feedback dialog during impersonation (#27802)
* fix: hide feature opt-in banner and feedback forms during impersonation

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix: keep opt-in banner visible during impersonation, only hide feedback forms

Co-Authored-By: sean@cal.com <Sean@brydon.io>

* fix: allow feedback form during impersonation in development mode

Co-Authored-By: sean@cal.com <Sean@brydon.io>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 10:28:03 +00:00
c58e1f4ae5 feat: add filter segment validation with useActiveFiltersValidator hook and refactor DataTableProvider (#27208)
* feat: add activeFilters validator to DataTableProvider for filter segment validation

- Add validateActiveFilters prop to DataTableProvider to filter out inaccessible values
- Create useActiveFiltersValidator hook in bookings module to validate filter values
- Integrate validator in bookings-view.tsx to validate userId, eventTypeId, teamId filters
- Add comprehensive tests for the filter validation logic

This provides a scalable solution for handling stale filter segment data by validating
filters at the caller level using already-fetched accessible resource IDs.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: add type guard for eventTypeIds to ensure number[] type

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: delay segment filter application until validator is ready

- Change useActiveFiltersValidator to return 'loading' state while data is fetching
- Add pending segment handling in DataTableProvider to delay filter application
- Expose isValidatorPending in context for consumers to disable queries
- Update BookingListContainer to disable bookings query while validator is pending

This prevents both errors from invalid filters and flash from fetching without filters.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: extract useSegmentManagement hook from DataTableProvider

- Extract segment management logic into dedicated useSegmentManagement hook
- Reduces DataTableProvider from ~500 lines to ~330 lines
- Use NuqsSetter type to match nuqs useQueryState setter signatures
- Maintains all existing functionality and type safety

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: export ActiveFiltersValidator types from data-table lib/types

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: import ActiveFiltersValidatorState from lib/types instead of hook

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* Revert "refactor: extract useSegmentManagement hook from DataTableProvider"

This reverts commit dd588ac4cfb1d709c71d1f621994a7e8f3118f33.

* refactor: split DataTableProvider into fine-grained context providers

- Create DataTableStateContext for raw nuqs state management
- Create DataTableSegmentContext for segment management
- Create DataTableFiltersContext for filter manipulation
- DataTableProvider now composes all providers with a bridge component
- Maintains backward compatibility via combined DataTableContext

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: apply segment filters when navigating back to page with existing URL state

When navigating back to a page with a segment already selected in the URL,
the segment was being marked as selected but its filters were not being
applied. This caused non-deterministic behavior where the filter segment
would sometimes not take effect.

The fix ensures that when segmentIdRaw exists in the URL and segments are
fetched, we also call applySegmentFilters() (with validator timing support)
instead of just setting the selectedSegment state.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: simplify filter validator to only handle multi-select

These filters are always multi-select, so remove unnecessary
single-select handling code and tests.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: cancel debounced search term on unmount

Cancel the debounced search term on unmount/dependency change to avoid
queued updates firing after the provider unmounts.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-10 10:38:12 +01:00
Udit TakkarandDevin AI 267686704d fix: availability page UI (#27825)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 09:06:21 +00:00
83354fbe18 fix(readme): correct 'therefor' typo to 'therefore' (#27816)
Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-10 09:04:35 +00:00
sean-brydon 892d53917d fix: pass onboardingfalse (#27806) 2026-02-10 09:03:17 +00:00
Dhairyashil Shinde 6f6c27b47d fixed header (#27794) 2026-02-10 14:10:13 +05:30
sean-brydonandDevin AI 9424649d6f fix: add isCompanyEmail check to organization upgrade path (#27813)
Users with personal emails (e.g. Gmail) could enter the org creation flow
at /settings/organizations/new but only hit the company email error at
checkout, with no way to fix it from the form. After changing their email
in settings, the cached store email was still used.

- Add server-side isCompanyEmail check in page.tsx to redirect early
- Add client-side check in CreateANewOrganizationForm with clear messaging
- Always use current session email for non-admin users (not cached store)
- Add tests for isCompanyEmail utility

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 06:15:28 +00:00
Carina WollendorferandDevin AI b03c00aded fix: remove duplicate label on team name input in team creation page (#27803)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-10 04:48:49 +00:00
Keith Williams e2e1ba096c chore: Use IF NOT EXISTS for index of App_RoutingForms_FormResponse (#27814) 2026-02-09 22:56:55 +00:00
Keith WilliamsandDevin AI 6a9b1ec3a8 perf: add composite index on (formId, createdAt) for App_RoutingForms_FormResponse (#27252)
* perf: add composite index on (formId, createdAt) for App_RoutingForms_FormResponse

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* chore: add migration for formId, createdAt composite index

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Update migration.sql

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 15:49:35 -03:00
Keith WilliamsandDevin AI 8b17df4621 refactor: Stop using Unkey for IP-based rate limiting (#27674)
* refactor: migrate IP-based rate limiting from Unkey to Cloudflare

Remove Unkey rate limiting for IP-based endpoints that will now be
handled by Cloudflare Enterprise Advanced Rate Limiting:

- Regular booking creation (createBooking:{hashedIP})
- Recurring booking creation (createRecurringBooking:{hashedIP})
- Instant meeting creation (instant.event-{hashedIP})
- Booking cancellation for unauthenticated users (api:cancel-ip:{hashedIP})
- Forgot password (forgotPassword:{hashedIP})
- Reset password (api:reset-password:{hashedIP})
- Signup (api:signup:{hashedIP})
- API v1 requests ({userId} with auto-lock)
- Global proxy rate limiting (common namespace)

Rate limiting that remains in Unkey (user/entity-based):
- Login (hashedEmail)
- Booking cancellation for authenticated users (api:cancel-user:{userId})
- 2FA setup/enable/disable (api:totp-*:{userId})
- SMS sending (team/org/user based)
- Email verification (various patterns)
- Team member operations (userId based)
- Routing forms (formId:responseHash)
- AI phone calls (userId based)

Also includes Cloudflare configuration proposal document with
recommended rules using JA4 fingerprinting for enhanced protection.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* chore: remove cloudflare proposal doc from PR

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* chore: remove cloudflare comments and keep common rate limiting type

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor: revert global middleware from PR #25080 and restore core rate limits

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor: restore instantMeeting rate limiting

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: restore email fallback in forgot-password rate limiting

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Remove the static file check

* refactor: add POST_METHODS_ALLOWED_API_ROUTES to proxy matcher

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* revert: restore API v1 rate limiting to original state

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* revert: restore reset-password, cancel, book/event, book/recurring-event to original state

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* refactor: use POST_METHODS_ALLOWED_API_ROUTES spread in matcher instead of hardcoded routes

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* revert: restore signup route to original state

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: update proxy matcher tests for POST_METHODS_ALLOWED_API_ROUTES spread

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Rename var

* refactor: revert matcher to static strings, add sync-check test for POST_METHODS_ALLOWED_API_ROUTES

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* removed dead routing forms rewrite code

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 15:49:26 -03:00
Lauris Skraucis edf9cd70dd fix: hide cal branding on platform workflows (#27385)
* fix: hide cal branding on platform workflows

* refactor: rely on existing with platform variables code

* revert: comment

* fix e2e

* chore: remove unit results
2026-02-09 13:46:52 -03:00
f66fffd13b feat: add routing trace seeding to seed-insights (#27782)
* feat: add routing trace seeding to seed-insights and standalone seed script

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* chore: remove standalone seed-routing-trace.ts (now in seed-insights)

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: track skipped routing trace creates for accurate log output

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 21:46:25 +05:30
82a4780145 feat: show routing trace dialog on assignment reason badge click (#27629)
* feat: show routing trace dialog on assignment reason badge click

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: remove duplicate RoutingTraceSheet rendering

- Remove RoutingTraceSheet from BookingListItem.tsx to avoid duplicate rendering
- Move RoutingTraceSheet in BookingActionsDropdown.tsx outside of isBookingFromRoutingForm condition
- Use booking.assignmentReason.length > 0 condition for RoutingTraceSheet rendering
- Remove unused isOpenRoutingTraceSheet getter and RoutingTraceSheet import from BookingListItem.tsx

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 10:39:34 -05:00
0a2d0854e7 fix: allow unmarking host as no-show (#27694)
* fix: allow unmarking host as no-show and filter invalid attendees in updateAttendees

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* revert: remove updateAttendees change per review feedback

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 13:14:53 +00:00
e04a394e1c fix: (booking-audit) Remove IS_PRODUCTION gate and add feature flag check in producer (#26524)
* fix: remove IS_PRODUCTION gate from BookingAuditProducer

Remove the IS_PRODUCTION check that was preventing booking audits from
being queued in production. Audits are still properly gated by:

1. Organization check: Audits are skipped for non-organization bookings
   (organizationId === null)
2. Feature flag: The BookingAuditTaskConsumer checks if the 'booking-audit'
   feature is enabled for the organization via featuresRepository.checkIfTeamHasFeature()

The IS_PRODUCTION gate was intentionally added to prevent logs from being
created in production while the action data versioning was being actively
reviewed and finalized. Without proper versioning handling, the Booking
History UI could crash when encountering unversioned data. Now that the
versioning system is in place, this gate can be safely removed.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: revert formatting, keep only IS_PRODUCTION removal

Reverts the unintended formatting changes from the previous commit.
Only removes the IS_PRODUCTION gate without changing indentation.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: add booking-audit feature flag check in producer to avoid unnecessary task creation

- Query booking-audit and booking-email-sms-tasker flags in parallel before fireBookingEvents
- Pass isBookingAuditEnabled through BookingEventHandler to producer's queueTask method
- Add conditional check in queueTask with debug log when skipping audit
- Reuse pre-queried isBookingEmailSmsTaskerEnabled flag instead of querying again

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: make isBookingAuditEnabled required and pass it through all booking audit flows

- Make isBookingAuditEnabled a required property in BookingAuditProducerService interface
- Update all BookingEventHandler methods to require isBookingAuditEnabled
- Add feature flag check in all flows that call booking audit:
  - handleSeats (seat booking/rescheduling)
  - RecurringBookingService (bulk bookings)
  - handleCancelBooking (booking cancellation)
  - handleConfirmation (booking acceptance)
  - roundRobinReassignment (automatic reassignment)
  - roundRobinManualReassignment (manual reassignment)
  - trpc handlers: addGuests, confirm, editLocation, requestReschedule
- Skip queueing audit tasks when feature is disabled with debug logging

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add featuresRepository dependency to RecurringBookingService DI module

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: make isBookingAuditEnabled optional for non-main flows

Keep feature flag check only in main flows (handleSeats, RegularBookingService, RecurringBookingService) which are frequently triggered. For other flows (handleCancelBooking, handleConfirmation, roundRobinReassignment, etc.), rely on the existing consumer-level check.

Changes:
- Revert feature flag check from non-main flows
- Make isBookingAuditEnabled optional in interface for non-main flow methods
- Keep isBookingAuditEnabled required for main flow methods (queueCreatedAudit, queueRescheduledAudit, queueSeatBookedAudit, queueSeatRescheduledAudit, queueBulkCreatedAudit, queueBulkRescheduledAudit)
- Update BookingEventHandlerService to use required params for main flows and optional for non-main flows

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: remove isBookingAuditEnabled from non-main flow methods

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: make isBookingAuditEnabled required in all BookingEventHandlerService methods

- Add isBookingAuditEnabled as required parameter in all BookingAuditProducerService interface methods
- Update BookingAuditTaskerProducerService to use simplified check (!params.isBookingAuditEnabled)
- Update BookingEventHandlerService to require isBookingAuditEnabled in all methods
- Update all callers to query booking-audit feature flag and pass isBookingAuditEnabled:
  - handleCancelBooking
  - handleConfirmation
  - roundRobinReassignment
  - roundRobinManualReassignment
  - addGuests.handler
  - confirm.handler
  - editLocation.handler
  - requestReschedule.handler
- Inject featuresRepository in API V2's booking-location.service.ts

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: update roundRobinReassignment tests to include isBookingAuditEnabled

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: update roundRobinManualReassignment tests to include isBookingAuditEnabled

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: inject featuresRepository in API V2 RecurringBookingService

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: import PrismaWorkerModule for PrismaFeaturesRepository dependency

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use booking's organization for feature flag check in addGuests handler

Use booking.user?.profiles?.[0]?.organizationId instead of user.organizationId
to check the booking-audit feature flag. This ensures the feature flag is
checked against the booking's organization rather than the actor's organization,
which is consistent with other handlers in this PR.

Addresses Cubic AI review feedback (confidence 9/10).

Co-Authored-By: unknown <>

* Add comment

* fix: use user.organizationId for feature flag check in addGuests handler

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: use booking's organizationId for feature flag check in addGuests handler

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: revert to user.organizationId for feature flag check in addGuests handler

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add isBookingAuditEnabled to onNoShowUpdated calls after main merge

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: add isBookingAuditEnabled to onNoShowUpdated calls and update tests

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 09:25:33 -03:00
emrysal b1b73f7fcc chore: release v6.1.13
Post release / release (push) Canceled after 0s
Release Docker / Prepare Release (push) Canceled after 0s
Release Docker / Release AMD64 (push) Canceled after 0s
Release Docker / Release ARM (push) Canceled after 0s
2026-02-09 11:56:07 +00:00
Benny JooandDevin AI 6287026638 fix: prevent 500 error when deleting calendar events with empty uid (#27500)
* fix: prevent 500 error when deleting calendar events with empty uid

This fix addresses a 500 error that occurs when trying to delete a Google
Calendar event with an empty event ID, which results in a malformed API URL.

Root cause: When calendar event creation fails or returns without an ID,
booking references were being created with empty uids. Later, when trying
to delete these events (e.g., during reschedule), the empty uid caused
a 404 from Google Calendar API which was then thrown as a 500 error.

Changes:
1. CalendarManager.deleteEvent: Added validation to skip deletion if
   bookingRefUid is empty, with appropriate error logging. This is a
   safety net for existing bad data in the database.

2. EventManager.create: Added filtering to exclude booking references
   with empty uids from being stored, with error logging to help
   diagnose the root cause of missing event IDs.

3. EventManager.updateLocation: Same filtering applied for consistency.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: revert EventManager filtering to preserve existing behavior

The test expects that booking references with empty uids are still created
when calendar event creation fails. This is intentional behavior to track
failed calendar syncs. The CalendarManager.deleteEvent fix handles the
deletion case gracefully by skipping the API call when uid is empty.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: throw ErrorWithCode instead of silently returning when bookingRefUid is empty

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: validate uid before calling calendar.deleteEvent to prevent 500 error

- Add uid check in lastAttendeeDeleteBooking.ts before calling calendar.deleteEvent
- Add uid check in EventManager.updateAllCalendarEvents before calling calendar.deleteEvent
- Revert CalendarManager.deleteEvent changes (validation at call sites is the proper fix)

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: add error logging safeguard in CalendarManager.deleteEvent for empty bookingRefUid

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: move bookingRefUid check before getCalendar call

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: prevent storing booking references with empty uid when calendar event creation fails

Root cause fix: Change the check from 'if (createdEvent)' to 'if (createdEvent.createdEvent)'
in createAllCalendarEvents to prevent failed calendar events from being added to results.

This prevents empty uids from being stored in the database in the first place, which
was causing 500 errors when trying to delete non-existent calendar events later.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* test: update test to expect no calendar reference when calendar event creation fails

The root cause fix changes behavior so that failed calendar events no longer
create booking references with empty uids. This test now expects an empty
references array when calendar event creation fails, which is the correct
behavior that prevents 500 errors later when trying to delete non-existent
calendar events.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: use createdEvent.success instead of createdEvent.createdEvent

Using success is more semantically clear since it explicitly checks the
success status rather than checking if the nested object exists.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* refactor: use optional chaining for createdEvent?.success

Using optional chaining is safer in case createdEvent is somehow undefined.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* revert: remove root cause fix to preserve backfilling script compatibility

The root cause fix (checking createdEvent?.success instead of createdEvent)
would break the backfilling script that relies on booking references with
empty uids to identify which bookings need backfilling.

This PR now only includes defensive checks to prevent 500 errors when
deleting calendar events with empty uids.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* revert

* fix

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 08:42:14 -03:00
Benny JooandDevin AI 96bec9f7b9 refactor: Move repositories from @calcom/lib to @calcom/features domain folders (#27570)
* refactor: move repositories from lib to features domain folders

- Move HolidayRepository to features/holidays/repositories
- Move PrismaTrackingRepository to features/bookings/repositories
- Move PrismaBookingPaymentRepository to features/bookings/repositories
- Move PrismaRoutingFormResponseRepository to features/routing-forms/repositories
- Move PrismaAssignmentReasonRepository to features/assignment-reason/repositories
- Move VerificationTokenRepository to features/auth/repositories
- Move WorkspacePlatformRepository to features/workspace-platform/repositories
- Move DTO files to their respective feature domains
- Merge lib DestinationCalendarRepository into features version
- Merge lib SelectedCalendarRepository into features version
- Update all import paths across the codebase

This follows the vertical slice architecture pattern by organizing
repositories by domain rather than by technical layer.

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update VerificationTokenService import path to new location

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: update test file imports to use new repository locations

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* mv

* fix structure

* fix

* refactor: merge unit tests for SelectedCalendarRepository into single file

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 08:41:04 -03:00
Rajiv SahalandDevin AI d4a059033e fix: restore listWithTeam query to include team events with userId set and add comprehensive tests (#27752)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 11:40:47 +00:00
Benny Joo eba0635a07 refactor: eliminate all @calcom/trpc/react imports and tRPC hooks from @calcom/features (#27728)
* migrate booker layout selector

* move schedule hooks and types

* migrate feature opt in components

* migrate feedback dialog

* update

* migrate schedule hooks

* migrate useSegments

* update

* update import paths

* fix import paths

* mv useTimesForSchedule back to features

* fix

* add useEvent to web

* remove the old file

* update imports

* clean up

* migrate Segment

* update imports

* update imports

* fix name

* fix tests

* fix

* fix

* update imports

* remove trpc/react

* remove trpc dependency from package.json

* rm

* wip

* wip

* fix types

* fix

* migrate PhoneInput

* mv LocationInput

* remove dead file

* update import paths

* rm dead import

* rm useApp hook

* cleanup

* wip

* restore

* wip

* remove dead code

* fix

* simplify

* fix

* fix

* fix

* fix

* fix

* fix

* format

* format

* restore

* remove prop
2026-02-09 08:39:28 -03:00
Anik Dhabal Babu 7b9168e3f2 fix: prevent "Closing rpc while fetch was pending" error in unit tests (#27725)
* test: prevent Closing rpc while

* update
2026-02-09 10:33:27 +00:00
9172fe6b1b fix: disable save button when workflow has no changes (#25973)
* fix: disable save button when workflow has no changes

* test: wait for save button to be enabled before clicking

* test: ensure input value is set before pressing Enter

* test fix

* fix: add shouldDirty to enable save button on name change

* test: clean up workflow test fixtures

* fix: disable save button when workflow has no changes

* test: update workflow E2E tests

* test: fix workflow E2E

* fix: enable save button when workflow form fields change

* fix tests

* fix: disable save button when workflow has no changes

* remove comments

* chore: improve fixture logic

* cleanup: remove unnecessary changes

* update workflow fixture to handle team workflow creation

---------

Co-authored-by: Pallav <90088723+Pallava-Joshi@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
Co-authored-by: Romit <romitgabani@icloud.com>
Co-authored-by: Romit <romitgabani1.work@gmail.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-09 08:55:49 +00:00
Aditya Vyas 19366700b3 fix: broken style on availability delete button (#27779)
* fix: broken style on availability delete button

* fix/final
2026-02-09 08:49:37 +00:00
b6916df671 test: add E2E tests for assignAllTeamMembers with attribute segment filters (#27680)
* test: add E2E tests for assignAllTeamMembers with attribute segment filters

Cover all 4 attribute types (SINGLE_SELECT, MULTI_SELECT, TEXT, NUMBER)
with booking flow verification plus edge cases (no match, all match).

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: use auto-retrying assertion for no-match edge case test

Replace flaky waitForTimeout(2000) + count check with Playwright's
toHaveCount(0, { timeout: 15000 }) which retries until availability
settles, preventing CI timing issues.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: add exclusion tests for members without attribute assigned

Add 4 new E2E tests covering the case where team members have no
attribute assigned at all (not just a different value). Each attribute
type (SINGLE_SELECT, MULTI_SELECT, TEXT, NUMBER) is tested to verify
that members without the attribute are excluded from the booking pool.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: add negation operator tests and restructure exclusion tests

- Restructure 'Members without attribute assigned' tests: assign
  matching attribute to teammate-1 (not owner) so round-robin can't
  coincidentally pass when the bug exists
- Add 4 negation operator tests (select_not_any_in, multiselect_not_some_in,
  not_equal for TEXT and NUMBER) that verify unassigned members should
  match negation filters. Marked with test.fail() as they confirm a
  known bug where getLogicResultForAllMembers skips members without
  attribute assignments entirely.
- Add edge case: no members have attribute assigned -> no available slots

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* test: remove test.fail() markers from negation tests after bug fix

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 14:07:49 +05:30
f819f6488e test: add E2E tests for routing form attribute conditions (#27681)
* feat: add comprehensive E2E tests for routing form attribute conditions

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: assert routedTeamMemberIds in URL instead of email in results

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: assert both routedTeamMemberIds in URL and email in results

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: include users without attribute assignments in exclusion condition evaluation

Users with no attribute assigned were excluded from the team members list
entirely, causing exclusion operators (not_equals, not_some_in, not_like,
not_between, etc.) to never match them. Now getAttributesAssignmentData
includes all team members, even those without attribute assignments.

Also adds unit tests and E2E tests for this scenario.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* fix: update getAttributes test to reflect new behavior for empty attributes

Users without attribute assignments are now included with empty attributes
so exclusion operators can match them. Updated test expectation accordingly.

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

* refactor: remove redundant usersWithAssignments code (fix already in _prepareAssignmentData from main)

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 14:02:22 +05:30
Benny Joo 29bb4fd497 refactor: remove 3 @calcom/web imports from @calcom/features by relocating blocklist UI and useEvent hook (#27775)
* migrate blocklist components to web

* migrate useEvent

* fix

* fix

* rm barrel file

* dead code
2026-02-09 08:02:42 +00:00
Ahmad YasserandDhairyashil cdf901fee3 fix: defer email validation to after first blur on signup form (#27765)
* fix: defer email validation to after first blur on signup form

Change react-hook-form validation mode from "onChange" to "onTouched"
so that the "Invalid email" error only appears after the user has
interacted with the field and moved away, not on every keystroke.
Password strength hints still update in real-time since onTouched
validates on change after the field has been touched (blurred once).

Fixes #19163

* test: add unit tests for signup email validation mode

Verify the onTouched form validation behavior:
- No error shown while user is typing
- Error appears only after blur with invalid email
- No error for valid email after blur
- Revalidation on each keystroke after first blur

* remove eslint comment

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2026-02-09 06:40:11 +00:00
Ahmad Yasser 3052cf5157 feat: add ARIA labels to time format and layout toggle controls (#27760)
Add aria-label to the TimeFormatToggle and LayoutToggle components
on the booking page so screen readers can identify these radio groups.
Uses existing translation keys "time_format" and "layout".

Fixes #20703
2026-02-09 06:13:27 +00:00
Hariom BalharaandDevin AI 0ec07b0005 fix: resolve flaky no-show-updated-action integration test (#27772)
- Remove unused attendeeIds field and unnecessary prisma.booking.findUnique from beforeEach
- Store booking.id in testData to avoid re-querying booking in test body
- Track additional attendee emails via additionalAttendeeEmails array for proper afterEach cleanup
- Remove fragile prisma.attendee.delete (throws P2025 on missing record) from test body
- Use deleteMany-based cleanupTestData for second attendee cleanup instead

The test was flaky because:
1. It used prisma.attendee.delete (singular) which throws if record is already gone
2. It re-queried the booking via findUnique mid-test which could fail if cascade-deleted
3. The second attendee email was not tracked in afterEach cleanup

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-09 05:10:37 +00:00
Ahmad Yasser e940aac2f1 fix: remove duplicate translation keys in common.json (#27769)
Remove 4 duplicate keys that existed in the English translations file:
- routing_forms: identical duplicate removed
- submit_feedback: kept "Submit feedback" (consistent casing)
- skip_trial: kept "Skip trial" (used as button label)
- availability_schedule: kept "Availability schedule" (sentence case),
  removed duplicate with inconsistent capitalization

Fixes #23478
2026-02-09 04:12:15 +00:00
Benny Joo 7ba749e496 fix: Atom build failing due to dependency on @calcom/web (#27757) 2026-02-08 20:31:18 +00:00
Ahmad YasserandSahitya Chandra 794046cf05 fix: prevent textarea resize overlapping buttons in rejection dialog (#27749)
* fix: prevent textarea resize overlapping buttons in rejection dialog

The rejection reason textarea in the booking rejection dialog allows
manual resizing via the drag handle, which can cause it to expand over
the dialog footer buttons. Adding resize-none prevents this overlap.

Fixes #17536

* Update RejectionReasonDialog.tsx

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-02-08 20:10:58 +00:00
60188bc66e fix(booking): make provider label and location link visible on mobile (#27463)
* fix(booking): make provider label and location link visible on mobile

* correct order

* remove comments

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2026-02-08 19:22:50 +00:00
an_ifrah24andRomit 466e7f2fa7 fix: removed extra scrollbar when selected checkbox field for booking form questions (#27592)
* fix: css property for the scroll bar and label for multi select

* chore

---------

Co-authored-by: Romit <romitgabani1.work@gmail.com>
2026-02-08 11:27:13 +00:00
Abhay MishraandDhairyashil 0b0a5478fb feat: Add action‑item support to mobile “More” page and added navigation to refer page (#26431)
* Add action‑item support to mobile “More” page and hide arrow on copy‑link button

* updated code

* fix code

* updated code

* remove unused import and formatting

---------

Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2026-02-07 13:57:24 +00:00
Abhay MishraandSahitya Chandra 0beadfa80b fix: allow deleting first time slot in availability schedule (#26448) (#27569)
* fix: allow deleting first time slot in availability schedule (#26448)

* code updated

---------

Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
2026-02-07 13:18:25 +00:00
Eunjae LeeandDevin AI a57fac7a78 docs: add code comment guidelines to AGENTS.md and update rule (#27729)
* docs: add code comment guidelines to AGENTS.md

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* docs: extract comment guidelines into agents/rules and reference from AGENTS.md

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-07 18:06:30 +05:30
22167d28b8 fix: prevent auto-install for OAuth apps in installation flow (#27567)
* fix: resolve organizer default conferencing app credential for location update

- Fix Google Meet credential lookup in EventManager to properly map 'google:meet' to 'google_video' type
- Add automatic credential ID resolution when selecting 'Organizer Default App' as location
- Fixes 'Location update failed' error when editing round-robin team event location to organizer default app (Google Meet) with multiple Google Calendar connections

Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>

* fix update

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-07 12:27:16 +00:00
Udit Takkar 129ea8d1f1 chore: enable agent teams feature (#27682) 2026-02-07 17:55:08 +05:30
Benny Joo e64fad8e34 refactor: remove 6 @calcom/trpc imports from packages/features (#27727)
* migrate booker layout selector

* move schedule hooks and types

* migrate feature opt in components

* migrate feedback dialog

* update

* migrate schedule hooks

* migrate useSegments

* update

* update import paths

* fix import paths

* mv useTimesForSchedule back to features

* fix
2026-02-07 09:05:09 -03:00
Sparky_AutonomousandSparky Autonomous aa5e90ab2a chore: Bail earlier when an invalid session is found (Fixes #15982) (#27609)
Co-authored-by: Sparky Autonomous <sparky@openclaw.ai>
2026-02-07 07:37:33 +00:00
Rajiv Sahal 321b07ab8b chore: troubleshooter atom docs (#27717) 2026-02-06 19:39:28 +00:00
3abde55b05 fix: Auth page in settings design fixed (#27294)
* fixed text issue

* matched style of api keys page

* o auth design fixed

---------

Co-authored-by: Rajiv Sahal <sahalrajiv-extc@atharvacoe.ac.in>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Romit <romitgabani@icloud.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
2026-02-07 00:52:11 +05:30
b45d7c15db fix: optional email validation (#27329)
* fix: validate optional email fields when input is provided #27299

* fix: validate optional email fields when input is provided

* fix: validate optional email fields when input is provided

* refactor: move empty value handling out of zod-utils

* fix: remove PII from error logs

* test: verify optional email allows empty submission

* test: e2e validation for optional email using url state

---------

Co-authored-by: Eunjae Lee <hey@eunjae.dev>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
2026-02-06 18:39:47 +00:00
68022f369c test: [Stacked] migrate findTeamMembersMatchingAttributeLogic to integration tests (#27697)
* Fix exclusion filter - include all team members

* Fix display when members aren't saved in the DB

* Update tests

* Use integration tests for findTeamMembersMatchingAttributeLogic for better behaviour testing

* Add test that verifies that it was working earlier and broken in b/w and not working again

* Revert changes to AddMembersWithSwitch.tsx

Co-Authored-By: joe@cal.com <j.auyeung419@gmail.com>

---------

Co-authored-by: Joe Au-Yeung <j.auyeung419@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 12:48:48 -05:00
Eunjae LeeandDevin AI b9c54f6661 docs: add Trigger.dev task implementation rule (#27712)
* docs: add Trigger.dev task implementation rule

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* docs: add specific file path references for CalendarsTasker and config examples

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-07 00:43:07 +09:00
Rajiv Sahal 8a17ebc2ef feat: Troubleshooter atom (#27497) 2026-02-06 17:34:58 +02:00
Everton Resende a71d62dc33 fix(ui): change phone booking display from Organizer Phone Number to Phone Call (#27636)
* fix(ui): change phone booking display from Organizer Phone Number to Phone Call

The label \"Organizer Phone Number\" was confusing for attendees on the
booking page, as it exposed internal terminology. Replaced with the
more user-friendly \"Phone Call\" label across the booking UI, companion
app, and test assertions.

Closes #13010

* fix: remove duplicate phone_call i18n key

The phone_call key already existed in en/common.json (line 1685,
Cal.ai Voice Agent section). Removed the duplicate entry we added.

Found by ai-codex review.
2026-02-06 15:28:38 +00:00
Benny JooandDevin AI a8ede7761f fix: use LOGO_DARK constant for generic OG image instead of hardcoded value (#27705)
* fix: use LOGO constant for generic OG image instead of hardcoded value

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* test: add unit tests for OgImages module

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix: remove unused LOGO import from OgImages test

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* fix

* test: update OgImages tests to reflect LOGO_DARK constant

Co-Authored-By: benny@cal.com <sldisek783@gmail.com>

* add comment

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 14:19:00 +00:00
Peer RichelsenandDevin AI 6a162e47c0 fix: remove unnecessary border from availability list view (#27683)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 15:15:49 +01:00
Joe Au-Yeung bc0ff0da8e fix: Exclusion attribute filter (#27669)
* Fix exclusion filter - include all team members

* Fix display when members aren't saved in the DB

* Update tests

* Undo change to member switch
2026-02-06 14:06:31 +00:00
38492d5839 fix: prevent layout shift in sticky navbar (#27256)
* fix navbar layout shift

* fix: adjust layout for iPad breakpoints

* fix: respect disableSticky for md+ header positioning

* Fix sticky header condition in Shell component

* Update apps/web/modules/event-types/components/EventTypeLayout.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Update apps/web/modules/shell/Shell.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Update apps/web/components/apps/layouts/AppsLayout.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Update apps/web/modules/event-types/components/EventTypeLayout.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Update packages/app-store/_components/AppCategoryNavigation.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Fix formatting in ShellMainAppDir component

* Update apps/web/modules/shell/Shell.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Adjust layout styles for Shell component

* Add dynamic header style based on banners height

* fix respect disableSticky and add spacing to navbar elements

* Refactor JSX structure in Shell component

* Refactor header div and sticky behavior

* Update AppsLayout.tsx

* remove sticky navbar from app store

* fix alignment

---------

Co-authored-by: Deepanshu Verma <deepanshuverma186@email.com>
Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
2026-02-06 13:21:06 +00:00
d80ee83da7 feat: redesign team creation flow to match onboarding (#27698)
* Revert "Revert "feat: redesign team creation flow to match onboarding-v3 design (#26733)""

This re-applies the team creation redesign from PR #26733 which was
previously reverted. Cherry-picked from 2540423ba3.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: check org/username slug when in org context

* fix: use expect(page).toHaveURL() instead of page.waitForURL() in team e2e test

Co-Authored-By: unknown <>

* fix: redirect URL

* fix: flag import

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 13:19:39 +00:00
369ec831fe feat: add comprehensive booking audit logs seed script (#27699)
* feat: add comprehensive booking audit logs seed script

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: remove dead code and use real UUID for impersonation context

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: seed audit logs for org user booking to enable UI testing

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: create dedicated booking for audit logs, only seed for org user

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: use realistic names and emails in audit log seed data

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: enable bookings-v3 global flag and booking-audit team flag in seed

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix or gcheck

* fix: add guard for empty profiles array in audit seed script

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 13:09:48 +00:00
sean-brydon bb6b99d9b1 feat: move platform active billing logic to services (#27704)
* wip

* feat: migrate from v2

* format

* remove plan
2026-02-06 12:45:40 +00:00
8a7cf24f90 feat(companion): add upcoming bookings widget for iOS and Android (#27199)
* feat(companion): add upcoming bookings widget for iOS and Android

- Add iOS widget using @bacons/apple-targets with SwiftUI
- Add Android widget using react-native-android-widget
- Configure App Groups for iOS data sharing between app and widget
- Create widget sync hook to update widget data when bookings change
- Widget displays up to 5 upcoming bookings with title, time, and attendee
- Widget refreshes every 15 minutes and when app goes to background

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix(companion): refactor useWidgetSync to avoid React Compiler limitation

Move conditional logic outside of try/catch block to fix React Compiler
error: 'Support value blocks (conditional, logical, optional chaining,
etc) within a try/catch statement'

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix(companion): fix widget data sync issues

- Fix Swift widget to read data as JSON string (format used by react-native-shared-group-preferences)
- Add fallback to read as raw Data for compatibility
- Fix query key mismatch by checking multiple common filter combinations
- Ensure widget finds cached bookings regardless of which filter the app used

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix(companion): use ExtensionStorage from @bacons/apple-targets for widget data

- Replace react-native-shared-group-preferences with ExtensionStorage
- ExtensionStorage properly stores data in iOS App Groups
- Add ExtensionStorage.reloadWidget() call to trigger widget refresh
- This ensures the widget picks up new data immediately

Co-Authored-By: peer@cal.com <peer@cal.com>

* feat(companion): add upcoming bookings widget for ios - all shapes (#27564)

* ios working widget

* fix(companion): remove sensitive data logging from widget storage

Remove console.log statements that were logging full widgetData payload
and formatted widget bookings containing attendee names and booking
details. This addresses security concerns identified by Cubic AI review
(confidence 9/10).

Co-Authored-By: unknown <>

* dark mode

* new look

* fix deeplink

* fix biome lint

* fix(companion): remove booking titles from console logs to avoid PII exposure

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* lock the versions and dev mode logging

* remove dynamic imports

* feat(companion): upcoming bookings widget android (#27689)

* companion-upcoming-bookings-widget-android

* fix(companion): remove stale relative countdowns and fix past-time clamping in Android widget

- Remove relative countdown text (In 15m, In 1h, Now) that becomes stale
  due to Android widget 30+ min update interval (Cubic violation 2)
- Remove Math.max(0, minutes) clamping that caused ended meetings to
  display as 'Now' indefinitely (Cubic violation 1)
- Simplify accent color logic to use startTimeISO directly
- Keep absolute time display (date + startTime) which remains accurate

Co-Authored-By: unknown <>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Dhairyashil <dhairyashil10101010@gmail.com>
Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
Co-authored-by: Volnei Munhoz <volnei@cal.com>
2026-02-06 12:32:46 +00:00
Anik Dhabal Babu 617cdea683 fix: fallback to cal video when Google Meet used without Google Calendar as default app (#27630)
* fallback to daily video

* add tests
2026-02-06 09:29:26 -03:00
Anik Dhabal Babu c6125f359d fix: event is not created on the Zoho Calendar when hideOrganizerEmail is enabled (#27675)
* fix: event not created

* Update CalendarManager.ts

* Add tests: packages/features/calendars/lib/CalendarManager.ts

Generated by Paragon from proposal for PR #27675

* Add tests: packages/features/calendars/lib/CalendarManager.test.ts

Generated by Paragon from proposal for PR #27675

* Export processEvent for testing and refactor logic

* Fix missing newline at end of CalendarManager.test.ts

Add missing newline at the end of the file.

* fix test
2026-02-06 12:28:22 +00:00
4a6d608b19 refactor: simplify link-as-an-app template and migrate 24 existing apps (#27215)
* refactor: simplify link-as-an-app template to config.json only

- Remove api/, components/, index.ts, package.json from link-as-an-app template
- Add externalLink field to AppMetaSchema for external URL configuration
- Update API handler to dynamically create handlers for external link apps
- External link apps no longer create credentials (just redirect to URL)
- Update CLI to handle externalLinkUrl field for link-as-an-app template
- CLI now skips package.json update for apps without package.json

Co-Authored-By: peer@cal.com <peer@cal.com>

* fix: simplify external link handler to bypass credential creation

External link apps now directly return the redirect URL without going
through the AppDeclarativeHandler type, avoiding type conflicts with
the createCredential return type requirement.

Co-Authored-By: peer@cal.com <peer@cal.com>

* refactor: migrate 24 external link apps to simplified structure

Migrated the following apps to use config.json with externalLink field
instead of api/add.ts handlers:

- amie, autocheckin, baa-for-hipaa, bolna, chatbase, clic, cron, deel
- elevenlabs, fonio-ai, framer, granola, greetmate-ai, lindy, millis-ai
- monobot, n8n, pipedream, raycast, retell-ai, synthflow, telli, vimcal
- wordpress

Each app now only contains: config.json, DESCRIPTION.md, static/
Removed: api/, components/, index.ts, package.json

Co-Authored-By: peer@cal.com <peer@cal.com>

* nit

* Fix merge conflict issue

* refactor: generate REDIRECT_APPS dynamically during app-store build

- Add logic to build.ts to detect apps with externalLink field
- Generate redirect-apps.generated.ts with list of redirect app slugs
- Update redirectApps.ts to import from generated file
- Revert [...]args].ts to original state (Flow 1 is preferred)

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: cast REDIRECT_APPS to readonly string[] for includes check

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Fix error with React

* Take exteral link URL as input

* deleted bun.lockb

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Hariom Balhara <hariombalhara@gmail.com>
2026-02-06 12:28:11 +00:00
54da93ab02 chore: Integrate mark-no-show booking audit (#26570)
* chore: Integrate mark-no-show booking audit

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Simplify host no-show audit and add comment for attendee actor

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Make actionSource required with ValidActionSource type and remove unnecessary comments

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove merge conflict markers from bookings.service.ts

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: implement SYSTEM as a booking audit source for background tasks, including no-show triggers.

* refactor: Move prisma query to BookingRepository for audit logging

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Conflict resolution

* refactor: introduce `handleMarkHostNoShow` for public viewer and standardize actor and action source parameters for no-show actions.

* refactor: Combine HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService into NoShowUpdatedActionService

- Create new NoShowUpdatedAuditActionService with combined schema supporting both noShowHost and noShowAttendee as optional fields
- Update BookingAuditActionServiceRegistry to use combined service with NO_SHOW_UPDATED action type
- Update BookingAuditTaskerProducerService with single queueNoShowUpdatedAudit method
- Update BookingAuditProducerService.interface.ts with combined method
- Update BookingEventHandlerService with single onNoShowUpdated method
- Update handleMarkNoShow.ts to use combined audit service
- Update tasker tasks (triggerGuestNoShow, triggerHostNoShow) to use combined service
- Add NO_SHOW_UPDATED to Prisma BookingAuditAction enum
- Remove old separate HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService files

This allows a single API action (e.g., API V2 markAbsent) that updates both host and attendee no-show status to be logged as a single audit event.

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* chore: Add migration for NO_SHOW_UPDATED audit action enum value

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Update no-show audit schema to use host and attendees array

- Rename noShowHost to host and noShowAttendee to attendees (remove redundant prefix)
- Change attendees from single value to array to support multiple attendees in single audit entry
- Update handleMarkNoShow.ts to create single audit entry for all attendees
- Update tasker tasks (triggerGuestNoShow, triggerHostNoShow) to use new schema
- Update display data types to reflect new schema structure

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Update schema to be more clear. Call onNoShowUpdated immediately after DB update as audit only cares about DB update, and this would avoid any accidental Audit update on DB change

* chore: accommodate schema changes and fix type errors for no-show audit

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update migration to remove old no-show enum values

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Use updated attendees in webhook payload for guest no-show

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove duplicate imports and fix actor parameter in bookings.service.ts

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Move booking query to BookingRepository and remove unused method

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: centralize no-show audit event firing and attendee fetching within `handleMarkNoShow` for improved clarity.

* fix: Build attendeesNoShow as Record with attendee IDs as keys

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Fix and add tests for handleMarkBoShow

* refactor: Move prisma queries to AttendeeRepository and BookingRepository

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Correct return type for updateNoShow method (noShow can be null)

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update handleMarkNoShow tests to mock new repository methods

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix triggerGuestNoShow

* refactor: Move triggerGuestNoShow queries to AttendeeRepository and add unit tests

- Add new methods to AttendeeRepository:
  - findByBookingId: Get attendees with id, email, noShow
  - findByBookingIdWithDetails: Get full attendee details
  - updateManyNoShowByBookingIdAndEmails: Update specific attendees
  - updateManyNoShowByBookingIdExcludingEmails: Update all except specific emails
- Refactor triggerGuestNoShow.ts to use AttendeeRepository instead of direct Prisma calls
- Add comprehensive unit tests for triggerGuestNoShow following handleMarkNoShow.test.ts pattern:
  - Mock repositories and external services
  - In-memory DB simulation
  - Test core functionality, audit logging, webhook payload, error handling, and edge cases

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Move triggerHostNoShow queries to repositories and delete unit test file

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Convert repository methods to use named parameters objects

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Enhance no-show handling by consolidating audit logging and updating repository interactions

- Refactor `buildResultPayload` to accept a structured argument for better clarity.
- Update `updateAttendees` to use a named parameter object for improved readability.
- Introduce `fireNoShowUpdatedEvent` to centralize no-show audit logging for both hosts and guests.
- Remove redundant methods and streamline attendee retrieval in `AttendeeRepository`.
- Add comprehensive unit tests for no-show event handling, ensuring accurate audit logging and webhook triggering.

* test: Add tests for handleMarkHostNoShow guest actor and unmarking host no-show

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: update attendeesNoShow validation to handle numeric keys

- Changed attendeesNoShow schema to use z.coerce.number() for key validation, ensuring string keys are correctly coerced to numbers.
- Updated test to validate attendeesNoShow data using numeric key comparison, improving robustness of the audit data checks.

* test: Add integration tests for NoShowUpdatedAuditActionService coerce fix

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: add graceful error handling for audit log enrichment

- Add hasError field to EnrichedAuditLog type
- Create buildFallbackAuditLog() method for failed enrichments
- Wrap enrichAuditLog() in try-catch to handle errors gracefully
- Add booking_audit_action.error_processing translation key
- Update BookingHistory.tsx to show warning icon for error logs
- Hide 'Show details' button for logs with hasError
- Add comprehensive test cases for error handling scenarios

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: Enhance booking audit action services with new display fields and improved validation

- Added "attendee_no_show_updated" and "no_show_updated" translations to common.json.
- Updated IAuditActionService to include new methods for handling display fields and migration.
- Enhanced NoShowUpdatedAuditActionService to differentiate between host and attendee no-show updates.
- Improved ReassignmentAuditActionService to ensure consistent handling of audit data.
- Refactored BookingAuditViewerService for better clarity and maintainability.

* refactor: Use attendeeEmail instead of attendeeId as key in audit data and store host's userUuid

- Updated schema to use attendee email as key instead of attendee ID because attendee records can be reused with different person's data
- Store host's userUuid in audit data with format: host: { userUuid, noShow: { old, new } }
- Updated fireNoShowUpdated to accept hostUserUuid parameter
- Added uuid field to BookingRepository.findByUidIncludeEventTypeAttendeesAndUser
- Updated NoShowUpdatedAuditActionService getDisplayFields to work with email-based keys
- Added attendeeRepository to DI modules for BookingAuditTaskConsumer
- Updated tests to match new schema format

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: Update integration tests to use new schema format with host.userUuid and email keys

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: correct audit schema for SYSTEM source and ensure attendee lookup by bookingId

- Fix schema inconsistency: use host.userUuid format instead of hostNoShow
- Add user.uuid to getBooking select for audit logging
- Log warning when hostUserUuid is undefined but host no-show is being updated
- Use email as key for attendeesNoShow (not attendee ID) to match schema
- Fetch attendees by bookingId before updating to ensure correct scoping
- Remove unused safeStringify import

* refactor: Change attendeesNoShow schema from Record to Array format

- Update NoShowUpdatedAuditActionService schema to use array format:
  attendeesNoShow: Array<{attendeeEmail: string, noShow: {old, new}}>
- Update handleMarkNoShow.ts to build attendeesNoShow as array
- Update common.ts fireNoShowUpdatedEvent to convert Map to array
- Update all tests to use new array format with attendeeEmail property

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Update attendeesNoShow schema to use array format in triggerNoShow tasks

- Refactor `triggerGuestNoShow` and `triggerHostNoShow` to replace Map with array for `attendeesNoShowAudit`.
- Update `fireNoShowUpdatedEvent` to handle the new array format for attendees.
- Ensure consistent data structure across no-show audit logging for better clarity and maintainability.

* fix: Update ReassignmentAuditActionService to use GetDisplayFieldsParams interface

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update ReassignmentAuditActionService tests to use GetDisplayFieldsParams interface

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Use handleMarkAttendeeNoShow for API v2 mark absent endpoint

- Export handleMarkAttendeeNoShow from platform-libraries
- Update API v2 bookings service to use handleMarkAttendeeNoShow with actionSource
- Add validation for userUuid before calling handleMarkAttendeeNoShow

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Enhance display fields structure in booking audit components

- Updated `BookingHistory.tsx` to allow for more flexible display fields, including optional raw values and arrays of values.
- Introduced `DisplayFieldValue` component for rendering display fields, improving clarity and maintainability.
- Adjusted `IAuditActionService` and `NoShowUpdatedAuditActionService` to align with the new display fields structure.
- Ensured consistent handling of display fields across the booking audit service for better data representation.

* fix: Remove debug code that duplicated first attendee in display fields

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Update attendee repository methods to use structured parameters

- Modified `updateNoShow`, `updateManyNoShowByBookingIdAndEmails`, and `updateManyNoShowByBookingIdExcludingEmails` methods to accept structured `where` and `data` parameters for better clarity and maintainability.
- Updated calls to these methods throughout the codebase to reflect the new parameter structure.
- Removed unused `findByIdWithNoShow` method and adjusted related logic to streamline attendee data retrieval.

* feat: Add infrastructure for no-show audit integration

- Add Prisma migrations for SYSTEM source and NO_SHOW_UPDATED audit action
- Add NoShowUpdatedAuditActionService with array-based attendeesNoShow schema
- Update BookingAuditActionServiceRegistry to include NO_SHOW_UPDATED
- Update BookingAuditTaskConsumer and BookingAuditViewerService
- Add AttendeeRepository methods for no-show queries
- Update IAuditActionService interface with values array support
- Update locales with no-show audit translation keys

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Add NO_SHOW_UPDATED to BookingAuditAction and SYSTEM to ActionSource types

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED from BookingAuditAction type to match Prisma schema

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update BookingAuditActionSchema to use NO_SHOW_UPDATED instead of HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Remove deprecated no-show audit services and unify to NoShowUpdatedAuditActionService

- Delete HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService
- Update BookingAuditProducerService.interface.ts to use queueNoShowUpdatedAudit
- Update BookingAuditTaskerProducerService.ts to use queueNoShowUpdatedAudit
- Update BookingEventHandlerService.ts to use onNoShowUpdated
- Add integration tests for NoShowUpdatedAuditActionService

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update test mock to match new AttendeeRepository.updateNoShow signature

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: rename handleMarkAttendeeNoShow to handleMarkNoShow and update related types

- Renamed `handleMarkAttendeeNoShow` to `handleMarkNoShow` for clarity.
- Updated type definitions to reflect the new naming convention.
- Modified the `markNoShow` handler to require `userUuid` and adjusted related logic.
- Enhanced the `fireNoShowUpdatedEvent` to accommodate changes in event type structure.
- Updated references across various files to ensure consistency with the new function name.

* handle null value

* fix: add explicit parentheses for operator precedence clarity

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Fix cubic reported bug

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 09:27:25 -03:00
08a5edd464 feat: nav item dropdown animation implemented (#26534)
* Nav Item dropdown animation Implemented

* minor issue resolved

* Dropdown

* fix: remove inert property from NavigationItem to resolve type check error

* add inert

* replace inert with visible/invisible class

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
Co-authored-by: Romit <romitgabani@icloud.com>
2026-02-06 17:37:19 +05:30
66fc0465bd fix: Form Builder Name Field Shows Default Label When Custom Label is Empty (#24201)
* removed previious pr ommit from thi sone

* fixed addressed issues

* fallback to non-empty label for variant fields

* fallback to default label

* normalize empty labels and fallback to default when label equals field name

* fix: initially use empty label for name field (fullName variant)

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: remove normalization of empty field labels in FormBuilder

* fix: enhance label handling in getTranslatedConfigVariants function

* Update apps/web/modules/event-types/components/tabs/advanced/FormBuilder.tsx

Co-authored-by: devin-ai-integration[bot] <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Pallav <90088723+Pallava-Joshi@users.noreply.github.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Sahitya Chandra <sahityajb@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-06 16:58:31 +05:30
b74dd3227c perf: Optimize DB calls and avoid N+1 queries in BookingAuditViewer (#26544)
* Integrate creation/rescheduling booking audit

* fix: add missing hostUserUuid to booking audit test data

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix-ci

* feat: enhance booking audit with seat reference

- Added support for seat reference in booking audit actions.
- Updated localization for booking creation to include seat information.
- Modified relevant services to pass attendee seat ID during booking creation.

* fix: update test data to match schema requirements

- Add seatReferenceUid: null to default mock audit log data
- Add seatReferenceUid: null to multiple audit logs test case
- Convert SEAT_RESCHEDULED test data to use numeric timestamps instead of ISO strings

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Allow nullish seatReferenceUid

* feat: enhance booking audit to support rescheduledBy information

- Updated booking audit actions to include rescheduledBy details, allowing tracking of who rescheduled a booking.
- Refactored related services to accommodate the new rescheduledBy parameter in booking events.
- Adjusted type definitions and function signatures to reflect the changes in the booking audit context.

* Avoid possible run time issue

* Fix imoport path

* fix failing test due to merge from main\

* Pass useruuid

* Refactor getDisplayTitle method signatures to use _params for consistency across audit action services. Update IAuditActionService to include dbStore in GetDisplayTitleParams for improved data handling during title retrieval.

* fix: extend bulk-fetching optimization to actor and impersonator enrichment

- Collect actor userUuids (for USER type actors) in collectDataRequirements
- Collect impersonator UUIDs from log.context.impersonatedBy
- Update enrichActorInformation to use dbStore.getUserByUuid() for USER actors
- Update enrichImpersonator to use dbStore.getUserByUuid()
- Update tests to verify findByUuids is called with correct aggregated UUIDs

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: Add infrastructure for no-show audit integration

- Add Prisma migrations for SYSTEM source and NO_SHOW_UPDATED audit action
- Add NoShowUpdatedAuditActionService with array-based attendeesNoShow schema
- Update BookingAuditActionServiceRegistry to include NO_SHOW_UPDATED
- Update BookingAuditTaskConsumer and BookingAuditViewerService
- Add AttendeeRepository methods for no-show queries
- Update IAuditActionService interface with values array support
- Update locales with no-show audit translation keys

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Add NO_SHOW_UPDATED to BookingAuditAction and SYSTEM to ActionSource types

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED from BookingAuditAction type to match Prisma schema

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Update BookingAuditActionSchema to use NO_SHOW_UPDATED instead of HOST_NO_SHOW_UPDATED and ATTENDEE_NO_SHOW_UPDATED

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Remove deprecated no-show audit services and unify to NoShowUpdatedAuditActionService

- Delete HostNoShowUpdatedAuditActionService and AttendeeNoShowUpdatedAuditActionService
- Update BookingAuditProducerService.interface.ts to use queueNoShowUpdatedAudit
- Update BookingAuditTaskerProducerService.ts to use queueNoShowUpdatedAudit
- Update BookingEventHandlerService.ts to use onNoShowUpdated
- Add integration tests for NoShowUpdatedAuditActionService

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Add data migration step for deprecated no-show enum values

Addresses Cubic AI review feedback (confidence 9/10): The migration now
includes an UPDATE statement to convert existing records using the
deprecated 'host_no_show_updated' or 'attendee_no_show_updated' enum
values to the new unified 'no_show_updated' value before the type cast.
This prevents migration failures if any existing data uses the old values.

Co-Authored-By: unknown <>

* fix: Use CASE expression in USING clause for enum migration

Fixes PostgreSQL error 'unsafe use of new value of enum type' by avoiding
the ADD VALUE statement and instead using a CASE expression in the ALTER
TABLE USING clause to convert deprecated enum values (host_no_show_updated,
attendee_no_show_updated) to the new unified value (no_show_updated) during
the type conversion.

Co-Authored-By: unknown <>

* fix: Remove dbStore usage from audit action services after merge

- Update CreatedAuditActionService to use userRepository.findByUuid directly
- Remove unused dbStore parameter from RescheduledAuditActionService
- Sync test file with prepare-for-no-show-audit branch

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Restore dbStore bulk-fetching optimization pattern

- Add dbStore parameter and getDataRequirements method to IAuditActionService interface
- Update CreatedAuditActionService to use dbStore.getUserByUuid() for bulk-fetched data
- Update RescheduledAuditActionService to accept dbStore parameter
- Update BookingAuditViewerService to:
  - Collect data requirements from all audit logs
  - Bulk-fetch users with findByUuids() before enrichment
  - Pass dbStore to action services and enrichment methods
- Update tests to verify findByUuids is called for bulk-fetching optimization

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Remove duplicate fireBookingEvents method in RecurringBookingService

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* revert: Remove formatting-only changes in audit action services

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: Make getDataRequirements required and fetch rescheduled logs early

- Make getDataRequirements a required method in IAuditActionService interface
- Add getDataRequirements to all action services that didn't have it
- Fetch rescheduled logs early to include their data requirements in bulk fetch
- Update ReassignmentAuditActionService to use dbStore pattern instead of repository
- Update NoShowUpdatedAuditActionService to use dbStore pattern
- Update tests to use new dbStore pattern
- Handle invalid data gracefully in collectDataRequirements

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* Remve unncessary variable

* feat: Implement Actor Strategy pattern for bulk-fetching attendees and credentials

- Add ActorStrategies.ts with strategy pattern for all 5 actor types
- Extend EnrichmentDataStore with StoredAttendee and StoredCredential types
- Add findByIds method to CredentialRepository for bulk-fetching
- Update BookingAuditViewerService to use strategy pattern:
  - Replace switch statement in enrichActorInformation with strategy dispatch
  - Update collectDataRequirements to collect attendeeIds and credentialIds
  - Update buildEnrichmentDataStore to bulk-fetch in parallel
- Update tests to use findByIds mock and reflect graceful handling of missing data

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Restore error-throwing for actors with missing required IDs

- USER actor now throws error when userUuid is missing
- ATTENDEE actor now throws error when attendeeId is missing
- Updated tests to expect hasError: true for fallback logs

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Restore original test assertions, only update mocks for bulk methods

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: Add contract verification tests for getDataRequirements

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Clean up imports and improve type definitions in BookingAuditTaskConsumer and BookingAuditViewerService

- Consolidated import statements for better readability
- Enhanced type definitions for clarity and consistency
- Updated method signatures to use destructured parameters for improved maintainability

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: Split contract verification tests into separate files per action service

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* test: Rename contract test files to .test.ts and merge into existing test file

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* feat: Add runtime validation to EnrichmentDataStore for undeclared data access

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Make declaredRequirements required and add ensureFetched helper

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Simplify EnrichmentDataStore with constructor + fetch() pattern

- Remove unused userIds and bookingUids from DataRequirements
- Remove unused getUserById and getBookingByUid methods
- Refactor constructor to accept requirements and repositories
- Add fetch() method that fetches data and populates maps
- Use Map keys as source of truth for declared requirements
- Update getters to throw when accessing undeclared data
- Add comprehensive unit tests for EnrichmentDataStore
- Update BookingAuditViewerService to use new API
- Update contractVerification.ts to remove unused tracking

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* refactor: Clean up imports and improve type definitions in BookingAuditTaskConsumer and BookingAuditViewerService

- Consolidated import statements for better readability
- Enhanced type definitions for clarity and consistency
- Updated method signatures to use destructured parameters for improved maintainability

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

* fix: Include contextRequirements in mergeDataRequirements and add accessedData assertions

- Fix bug where contextRequirements (impersonator UUIDs) were not merged
- Add accessedData assertions to CreatedAuditActionService.test.ts
- Add accessedData assertions to ReassignmentAuditActionService.test.ts

Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-06 16:08:38 +05:30
39135f84ef fix: call history to free users (#27473)
* fix: call history to free users

Signed-off-by: Jagadish Madavalkar <jagadish.me07@gmail.com>

* bypass paywall for insights/call-history

* improve naming

---------

Signed-off-by: Jagadish Madavalkar <jagadish.me07@gmail.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
Co-authored-by: Romit <romitgabani@icloud.com>
2026-02-06 15:41:01 +05:30
Eunjae LeeandClaude Opus 4.5 512002aaef refactor: replace FeaturesRepository with DI-based feature repositories (#27200)
* refactor: replace FeaturesRepository with DI-based feature repositories

Migrate from the legacy FeaturesRepository pattern to separate DI-based repositories:
- Add checkIfFeatureIsEnabledGlobally to IFeatureRepository
- Add getTeamsWithFeatureEnabled to ITeamFeatureRepository
- Update CalendarSubscriptionService to use featureRepository, teamFeatureRepository, and userFeatureRepository
- Update SelectedCalendarRepository.findNextSubscriptionBatch to filter by teamIds instead of featureIds
- Update OnboardingPathService to use DI via getFeatureRepository()
- Remove prisma parameter from OnboardingPathService callsites

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: update tests to use new DI-based feature repositories

Update CalendarSubscriptionService and SelectedCalendarRepository tests
to use the new separate repository interfaces:
- featureRepository for global feature checks
- teamFeatureRepository for team-level feature checks
- userFeatureRepository for user-level feature checks

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: update API routes to use DI-based feature repositories

Update cron and webhook routes to use the new separate repository
interfaces instead of the combined FeaturesRepository.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: remove prisma arg from getGettingStartedPathWithParams call

The OnboardingPathService method no longer requires a prisma argument
as it now uses DI containers internally.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* test: update route tests to expect new DI-based feature repositories

Update service instantiation tests to expect featureRepository,
teamFeatureRepository, and userFeatureRepository instead of the
old featuresRepository.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: optimize global feature check and add guard in checkForNewSubscriptions

- Use targeted select for only `enabled` field in checkIfFeatureIsEnabledGlobally
- Add global feature flag guard in checkForNewSubscriptions to avoid unnecessary
  DB queries and API calls when the cache feature is globally disabled

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* remove redundant comment

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-06 09:34:03 +00:00
Pedro CastroandDevin AI cb36fc201f fix: add URL validation to webhook endpoints (#26593)
Validates webhook URLs on create and update:
- HTTPS required (HTTP allowed for self-hosted and E2E)
- Blocks private IP ranges and localhost
- Blocks cloud metadata endpoints

Existing webhooks are preserved: validation only applies when URL is created or changed.

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 16:18:10 -03:00
Anik Dhabal Babu c57b517555 optimize organization member removal (#27660) 2026-02-05 17:11:57 +00:00
7226f1e4c0 fix: ux audit changes (#26875)
* fix: ux audit changes

* fix: remove locale-insensitive toLowerCase() on translation

Remove .toLowerCase() call on t('minutes') translation as it is
locale-insensitive and can corrupt translations (e.g., Turkish
dotted/dotless 'i'). The translation itself should provide the
desired casing.

Addresses Cubic AI review feedback with confidence 9/10.

Co-Authored-By: unknown <>

* fix: redirect url tool tip not working

* fix: type check

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 13:37:59 -03:00
Keith WilliamsandDevin AI b0835e8ae3 perf: reduce team page client payload with minimal data serialization (#27656)
* perf: optimize team page data fetching by reducing host user data

For team view pages (/team/[slug]), event type hosts only need minimal
user data for avatar display (id, name, username, avatarUrl).

Previously, the full userSelect was used which included:
- teams (with nested team data)
- credentials (with app and destinationCalendars)
- email, bio

This optimization reduces data transfer significantly for teams with
many event types and hosts. With 441K requests and 54GB outgoing data
(~128KB per request), even small reductions per request add up.

The full userSelect is still used when !isTeamView to support the
connectedApps feature.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* perf: optimize team page serialization to reduce data transfer

- Replace spread operators with explicit field selection for eventTypes
- Only send minimal user data needed for UserAvatarGroup: name, username, avatarUrl, profile
- Override eventTypes in return props with minimalEventTypes
- Reduces per-request data transfer by excluding unnecessary fields like email, bio, teams, credentials

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: add missing fields needed by EventTypeDescription component

Add metadata, seatsPerTimeSlot, requiresConfirmation to minimalEventTypes
Add id to user object for proper key handling

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* revert: remove serialization changes that broke TypeScript types

Keep only the query-level optimization in queries.ts which reduces
database load by fetching minimal user data for event type hosts
when isTeamView=true.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* perf: reduce team page client payload with explicit DTO types

- Create TeamPage.types.ts with explicit DTO types for minimal data
- Update getServerSideProps.tsx to return only fields needed by the UI
- Update team-view.tsx to use explicit types instead of inferSSRProps

This reduces the data sent to the client by:
- Event types: only id, title, slug, description, length, schedulingType,
  recurringEvent, metadata, requiresConfirmation, seatsPerTimeSlot
- Event type users: only id, name, username, avatarUrl, avatar, profile
- Members: only fields needed by Team component
- Children: only slug and name
- Parent: only id, slug, name, isOrganization, isPrivate, logoUrl

Combined with the query-level optimization, this should significantly
reduce the ~128KB average payload per request.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* Revert: explicit DTO approach due to type compatibility issues

The explicit DTO types broke compatibility with existing components
(EventTypeDescription, UserAvatarGroup) which expect specific type
structures. Keeping only the query-level optimization.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* perf: reduce team page client payload with minimal data serialization

- Update EventTypeDescription to accept minimal type (only fields actually used)
- Update UserAvatarGroup to accept minimal user type
- Update UserAvatar to accept minimal profile type
- Update Team component to accept minimal member type
- Update getServerSideProps to explicitly select only needed fields

This reduces the ~128KB client payload by removing unused fields from:
- Event types: removed hidden, price, currency, lockTimeZoneToggleOnBookingPage, etc.
- Event type users: only send name, username, avatarUrl, avatar, profile.username, profile.organization.slug
- Team members: only send fields needed by Team component
- Team parent/children: only send fields needed for display

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: revert component type changes, keep serialization optimization

- Revert EventTypeDescription, UserAvatarGroup, UserAvatar, Team component types to original
- Keep serialization optimization in getServerSideProps.tsx
- Add missing fields (price, currency, hidden, etc.) for EventTypeDescription compatibility
- Add full profile structure for UserAvatarGroup compatibility

This reduces client payload by explicitly selecting only needed fields while
maintaining type compatibility with existing component usages.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* fix: add missing fields for component type compatibility

- Add lockedTimeZone and canSendCalVideoTranscriptionEmails for EventTypeDescription
- Add organizationId to members for Team component MemberType
- Add name, calVideoLogo, bannerUrl to organization for UserProfile type
- Reorder fields to match baseEventTypeSelect structure

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 12:03:37 -03:00
MorganandDevin AI 295058d123 fix: use Object.prototype.hasOwnProperty.call for safe property checks (#27661)
The error 'TypeError: value.hasOwnProperty is not a function' can occur
when objects are created without the standard Object prototype (e.g., via
Object.create(null) or certain parsing methods). Using
Object.prototype.hasOwnProperty.call() is the safe way to check for
property existence on any object.

Fixed in:
- GetSlotsInputPipe (isById, isByUsernameAndEventTypeSlug, isByTeamSlugAndEventTypeSlug)
- CancelBookingInputPipe (isCancelSeatedBookingInput)
- CreateBookingInputPipe (isRecurringBookingInput, isInstantBookingInput)

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 11:11:43 -03:00
2e9191fcad fix: open Join button in default browser instead of in-app browser (#27455)
* fix: open Join button in default browser instead of in-app browser

Co-Authored-By: peer@cal.com <peer@cal.com>

* feat(companion): open join in default browser (#27655)

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Dhairyashil Shinde <93669429+dhairyashiil@users.noreply.github.com>
2026-02-05 17:39:26 +05:30
an_ifrah24 75cd509106 fix: cleaned the extra space in description before saving to avoid word break (#27632) 2026-02-05 12:20:07 +01:00
Eunjae Lee de24e0a232 fix: show bookings-v3 opt-in banner (#27653) 2026-02-05 11:13:15 +00:00
2364cff54d feat: custom feedback dialog for feature opt-in (#27578)
* feat: add delayed formbricks tracking for feature opt-in

Adds delayed Formbricks survey tracking for feature opt-in. When a user
opts into a feature, this allows triggering a Formbricks action after a
configurable delay (e.g., 24 hours later) to collect feedback once
they've had time to use the feature.

Key changes:
- Added `formbricks` config option to `OptInFeatureConfig` interface
  with `actionName` and `delayMs` properties
- Created `useFormbricksOptInTracking` hook that handles the delayed
  tracking logic
- Added `isFeatureTracked` / `setFeatureTracked` storage helpers to
  prevent duplicate tracking
- Integrated the tracking hook into `useFeatureOptInBanner`

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* upgrade formbricks

* feat: replace formbricks popup with custom feedback dialog

Instead of using Formbricks' built-in popup, we now show a custom
Cal.com-styled feedback dialog that submits responses directly to
Formbricks API via tRPC mutation.

- Add FeedbackDialog component with emoji rating selector
- Add feedback tRPC router for server-side Formbricks submission
- Update useFormbricksOptInTracking to return dialog state
- Add survey config fields (surveyId, questions) to config

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: position feedback dialog at bottom-right corner

- Use base-ui Dialog primitives for custom positioning
- Position dialog at bottom-right to avoid Intercom overlap
- Use z-index 10000 (below Intercom's high z-index)
- Keep blocking backdrop for modal behavior
- Use i18n keys for title/description
- Add survey IDs for bookings-v3 feedback

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add i18n keys for feedback dialog title/description

Allow each feature to specify custom i18n keys for the feedback dialog
title and description via the formbricks config.

- Add titleKey/descriptionKey to formbricks config interface
- Pass i18n keys through feedbackDialogProps
- Add bookings_v3_feedback_title/description translation keys

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: move FeedbackDialog into FeatureOptInBannerWrapper

Better encapsulation - consumers of the feature opt-in banner
no longer need to handle the feedback dialog separately.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: add 5 second delay before showing feedback dialog

Ensures the page has time to finish loading before showing
the feedback dialog, avoiding showing it while skeletons
are still visible.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: simplify feedback dialog UI

- Remove redundant question labels
- Add "(optional)" to comment placeholder

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: remove emoji button borders and add footer gap

- Remove borders from rating emoji buttons
- Add proper gap between textarea and footer (pb-4)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: delayMs is opt-in waiting period, not setTimeout delay

delayMs represents the minimum time that must pass since opt-in
before showing the feedback form (e.g., 3 days). If not enough
time has passed, we skip showing the form entirely instead of
setting a long setTimeout.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* feat: custom feedback dialog for feature opt-in

- Replace Formbricks popup with Cal.com-styled dialog
- Add configurable delay (waitAfterDays) before showing feedback
- Position dialog at bottom-right, non-blocking
- Add localStorage tracking to prevent duplicate feedback
- Add device targeting (showOn: desktop/mobile/all)
- Create tRPC endpoint for Formbricks API submission
- Use proper logger for error handling

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* refactor: rename tracking terminology to feedback

- Rename useFormbricksOptInTracking → useOptInFeedback
- Rename FormbricksOptInTrackingResult → OptInFeedbackState
- Rename formbricksTracking property → feedback
- Rename FormbricksTrackingState → FeedbackState

We no longer "track" events to Formbricks. Instead, we show
our custom feedback dialog when conditions are met.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: set waitAfterDays to 3 for production feedback delay

Co-Authored-By: unknown <>

* fix: update formbricks JS SDK usage for v3.0.0

The @formbricks/js SDK v3.0.0 changed its API:
- setup() no longer accepts debug, userId, or attributes
- Use setUserId() and setAttributes() after setup instead
- track() now expects { hiddenFields: ... } or undefined

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 11:01:14 +00:00
80e07a8d35 fix: add oauth client owner email to admin view (#27243)
* add owner email to admin oauth view

* fix type error

* fix oauth flow with sign up

* improve e2e tests

* fix: use dynamic user email in OAuth client e2e test

The test 'editing redirect uri of an approved client triggers reapproval'
creates a new user and assigns the OAuth client to that user, but was
incorrectly expecting 'admin@example.com' as the owner email. Changed to
use user.email to correctly validate the owner email matches the created
user.

Addresses Cubic AI review feedback (confidence: 9/10)

Co-Authored-By: unknown <>

---------

Co-authored-by: CarinaWolli <wollencarina@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 10:39:29 +00:00
Eunjae LeeandDevin AI 357c2882ad refactor: apply biome formatting to several packages (#27439)
* refactor: apply biome formatting to Phase 1 packages

Packages formatted:
- packages/app-store-cli
- packages/config
- packages/dayjs
- packages/debugging
- packages/embeds/embed-react
- packages/embeds/embed-snippet
- packages/kysely
- packages/platform/constants
- packages/platform/utils
- packages/testing
- packages/tsconfig

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: restore non-null assertions in embed-snippet to fix type error

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: remove ESM import from CommonJS config file

Biome incorrectly added 'import process from node:process' to a CommonJS
file that uses require(). This breaks Jest which expects CommonJS syntax.
The process global is already available in Node.js without explicit import.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* refactor: exclude packages/embeds from Phase 1 formatting

Per user request, reverting all biome formatting changes in packages/embeds
to handle separately.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

* fix: restore const enum for BookingLocations

Biome changed 'const enum' to 'enum' which is a semantic change.
Reverting to keep the PR purely formatting-only.

Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 07:24:34 -03:00
c652c61e0c feat: refactor UI to use coss + coupons UI (#27647)
* feat: refactor UI to use coss + coupons UI

* fix: use TRPCError and remove sensitive logging in createCoupon handler

- Replace plain Error with TRPCError for consistent tRPC error handling
- Use INTERNAL_SERVER_ERROR for missing env configuration
- Use UNAUTHORIZED for permission denied errors
- Use BAD_REQUEST for API failure errors
- Remove console.warn that logged username (sensitive info)

Co-Authored-By: unknown <>

* feat: add copy button and fix 0 on % off

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 10:05:57 +00:00
1ad4ad6e4e feat: High Water Mark (HWM) billing for monthly subscriptions (#27559)
* wip

* fix: claue reveiew commentsd

* add seed test

* fix: seed test plus subscriptin undefined in webhook

* chore: udpate triggr

* Integration test + HWM seed script

* add feature flag for hmw

* Remove redudant docs

* feat: add hwm-seating feature flag for high water mark billing

- Add new hwm-seating feature flag to control HWM billing logic
- Update HighWaterMarkService to use hwm-seating flag
- Update SeatChangeTrackingService to use hwm-seating flag
- Update BillingPeriodService to use hwm-seating flag
- Add flag to migration SQL
- Enable flag in seed script and integration test

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix: add hwm-seating to useFlags and fix test mocks

- Add hwm-seating to useFlags.ts initial data
- Add shouldApplyHighWaterMark mock to TeamBillingService tests

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

* fix test

* feat: move to invoice paid subscription

* fix: transactions for transiants updates + reusable util

* fix: address Cubic AI review feedback for HWM billing

- Fix dotenv import hoisting in seed-hwm-test.ts by using side-effect import
- Remove logging of sensitive information (password/emails) in seed script
- Fix incorrect newHighWaterMark return value when update is not performed

Co-Authored-By: unknown <>

* add additional unit tests

* improve DI

* fix migration + restore package.json trigger update

* feat:move to featurerepo+update tests

* fix mocks

* fix DI calls

* revert faeturerepo to featuresrepository

* fix: pass featureRepository to BillingPeriodService and HighWaterMarkService

- Fix TeamBillingService.ts: pass featureRepository to BillingPeriodService constructor
- Fix _invoice.upcoming.ts: pass featureRepository to HighWaterMarkService constructor
- Fix hwm-webhook-utils.ts: pass featureRepository to HighWaterMarkService constructor

These services require featureRepository for feature flag checks but production
call sites were missing this required dependency, causing runtime errors.

Addresses Cubic AI review feedback on PR #27559

Co-Authored-By: unknown <>

* fix import

* update feature repo usage to features

* remove test thats mocking the wrong stuff

* revert RegularBookingService changes

* remove hide branding

* remove change in redudant file

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 09:56:31 +00:00
Benny Joo 249065851b refactor: Break useCreateEventType hook into web-specific and platform-specific ones (#27522)
* migrate useCreateEventType hook to web

* fix

* fix

* fix import
2026-02-05 15:06:05 +05:30
Morgan cf55b5b462 fix: ensure default calendars domain (#27645)
* fix: ensure default calendars delegation credential domain

* fix: ensure default calendars delegation credential domain
2026-02-05 09:22:29 +00:00
bd25cba89c refactor: OAuth 2.0 endpoints (#27442)
* refactor: combine exchange and refresh into token endpoint

* refactor: controller error handling

* refactor: use snake_case

* refactor: use snake_case

* refactor: use snake case

* refactor: token endpoint accepts application/x-www-form-urlencoded

* refactor: token endpoint accepts application/x-www-form-urlencoded

* refactor: flat token response data

* refactor: error structure

* refactor: client_id in the body

* fix: address Cubic AI review feedback on OAuth2 endpoints

- Fix getClient endpoint to use proper REST API error format instead of OAuth token error format (confidence 9/10)
- Add missing space after comma in error format string in token.input.pipe.ts (confidence 9/10)
- Support both camelCase and snake_case inputs in authorize endpoint for backward compatibility (confidence 10/10)
- Restore legacy /exchange and /refresh endpoints alongside new /token endpoint for backward compatibility (confidence 10/10)
- Add OAuth2TokensResponseDto for legacy endpoint wrapped responses
- Add OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput for legacy endpoints

Co-Authored-By: unknown <>

* fix: address additional Cubic AI feedback on OAuth2 endpoints

- Log errors when status code >= 500 in handleClientError (confidence 9/10)
- Add Cache-Control: no-store and Pragma: no-cache headers to legacy /exchange and /refresh endpoints (confidence 9/10)

Co-Authored-By: unknown <>

* docs

* Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints"

This reverts commit 39cc4aa3ebb9e59a171541d7010398425995ed89.

* Revert "fix: address Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 97bf593186db04c0859f9ca30950c9e3e524019d.

* docs

* fix: address Cubic AI review feedback on OAuth2 endpoints

- Fix getClient to use handleClientError instead of handleTokenError (confidence 10)
- Restore legacy /exchange and /refresh endpoints for backward compatibility (confidence 9)
- Fix RFC 6749 error format: use human-readable messages in error_description (confidence 9)
- Fix errorDescription in OAuthService to use OAUTH_ERROR_REASONS mapping (confidence 9)

Co-Authored-By: unknown <>

* fix: address additional Cubic AI feedback on OAuth2 endpoints

- Fix security issue: Replace 'CALENDSO_ENCRYPTION_KEY is not set' with generic 'Internal server configuration error' message (confidence 10/10)
- Fix backward compatibility: Create OAuth2LegacyTokensDto with camelCase properties for legacy /exchange and /refresh endpoints (confidence 9/10)
- Skipped: RFC 6749 error field issue (confidence 8/10, below threshold)

Co-Authored-By: unknown <>

* e2e

* Revert "fix: address additional Cubic AI feedback on OAuth2 endpoints"

This reverts commit a080e93f07aaf5a7dcf81fe605012cb7ebcdc192.

* Revert "fix: address Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 04986a16c981521ca97069152457bf521a9ee45f.

* fix: re-apply Cubic AI review feedback on OAuth2 endpoints

- Restore OAuth2LegacyExchangeInput and OAuth2LegacyRefreshInput classes
- Restore legacy /exchange and /refresh endpoints in OAuth2Controller
- Restore OAuth2LegacyTokensDto and OAuth2TokensResponseDto classes
- Restore OAUTH_ERROR_DESCRIPTIONS mapping in oauth2-error.service.ts
- Restore OAUTH_ERROR_REASONS lookup in OAuthService.ts mapErrorToOAuthError
- Fix encryption_key_missing error to not expose internal env var name

Addresses Cubic AI feedback with confidence >= 9/10:
- Comment 32 (9/10): Legacy endpoints and input classes
- Comment 34 (9/10): Error description mapping in OAuthService
- Comment 35 (10/10): OAUTH_ERROR_DESCRIPTIONS in error service

Skipped (confidence < 9/10):
- Comment 33 (8/10): getClient handleTokenError vs handleClientError

Co-Authored-By: unknown <>

* Revert "fix: re-apply Cubic AI review feedback on OAuth2 endpoints"

This reverts commit 416bef9c931d9a7ed78c65a70a3425550d61b151.

* delete unused file

* fix: e2e tests

* address cubic review

* fix: address Cubic AI review feedback on OAuth2 exception filter

- Fix header case sensitivity: use lowercase 'x-request-id' instead of 'X-Request-Id' since Express lowercases all request headers
- Redact request body in error logs to prevent exposing sensitive OAuth2 credentials like client_secret, password, and refresh_token

Co-Authored-By: unknown <>

* docs: api v2 oauth controller docs

* chore: remove authorize endpoint

* refactor: remove scope from docs

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-02-05 10:16:15 +02:00
DeepanshuandDeepanshu Verma bcbb714ea9 fix: toggle chevron icon direction in filter segment dropdown (#27641)
* fix: chevron toggle in filter segment dropdown

* fix: restore disabled state behavior for filter segment dropdown

---------

Co-authored-by: Deepanshu Verma <deepanshuverma186@email.com>
2026-02-05 06:57:09 +00:00
9a5323bbb6 feat: add delete confirmation dialog to webhook list items (#26305)
* feat: add delete confirmation dialog to webhook list items

* adds appname for translation key used in alert

* extract delete wehook dialog into separate component

* add e2e test

* chore update e2e locator

---------

Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Romit <85230081+romitg2@users.noreply.github.com>
Co-authored-by: Romit <romitgabani@icloud.com>
2026-02-05 08:32:51 +05:30
Alex van Andel 9a287ac876 Revert "fix: add input validation to analytics app schemas (#26976)"
This reverts commit c43c48b1a8.
2026-02-05 01:01:33 +00:00
Alex van Andel a8e1cbeeb5 Revert "fix: handle null/undefined tracking IDs in analytics schemas (#27625)"
This reverts commit 04e828358a.
2026-02-05 01:00:42 +00:00
2360 changed files with 69342 additions and 86321 deletions
+5
View File
@@ -0,0 +1,5 @@
{
"env": {
"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
}
}
-57
View File
@@ -1,57 +0,0 @@
# EAS Build ignore file for monorepo
# Only upload the companion app folder
# ===========================================
# IGNORE EVERYTHING AT ROOT LEVEL
# ===========================================
/*
# ===========================================
# EXCEPT THE COMPANION APP
# ===========================================
!companion
# ===========================================
# BUT IGNORE THESE INSIDE COMPANION
# ===========================================
# Native folders - EAS generates these during builds (~2.1 GB)
companion/ios
companion/android
# Dependencies - EAS installs these during builds (~1.6 GB)
companion/node_modules
# Expo build cache
companion/.expo
companion/dist
companion/web-build
# Metro
companion/.metro-health-check*
# WXT Chrome Extension outputs (not needed for mobile builds)
companion/.output
companion/.wxt
companion/dev
# Kotlin cache
companion/.kotlin
# Build artifacts
companion/*.jks
companion/*.p8
companion/*.p12
companion/*.key
companion/*.mobileprovision
# Debug logs
companion/*.log
# TypeScript build info
companion/*.tsbuildinfo
# Environment files
companion/.env
companion/.env.*
!companion/.env.example
+2
View File
@@ -209,11 +209,13 @@ NEXT_PUBLIC_STRIPE_PREMIUM_PLAN_PRICE=
NEXT_PUBLIC_IS_PREMIUM_NEW_PLAN=0
NEXT_PUBLIC_STRIPE_PREMIUM_NEW_PLAN_PRICE=
STRIPE_TEAM_MONTHLY_PRICE_ID=
STRIPE_TEAM_ANNUAL_PRICE_ID=
NEXT_PUBLIC_STRIPE_CREDITS_PRICE_ID=
ORG_MONTHLY_CREDITS=
STRIPE_TEAM_PRODUCT_ID=
# It is a price ID in the product with id STRIPE_ORG_PRODUCT_ID
STRIPE_ORG_MONTHLY_PRICE_ID=
STRIPE_ORG_ANNUAL_PRICE_ID=
STRIPE_ORG_PRODUCT_ID=
# Used to pass trial days for orgs during the Stripe checkout session
STRIPE_ORG_TRIAL_DAYS=
+9
View File
@@ -9,6 +9,7 @@
/apps/web/lib/core/**/* @calcom/Foundation
/apps/web/lib/booking.ts @calcom/Foundation
/apps/web/lib/handleOrgRedirect.ts @calcom/Foundation
/apps/web/modules/shell/Shell.tsx @calcom/Foundation
/apps/web/proxy.ts @calcom/Foundation
/deploy/**/* @calcom/Foundation
/packages/app-store/applecalendar/**/* @calcom/Foundation
@@ -36,3 +37,11 @@
/packages/trpc/server/routers/viewer/bookings/get.handler.ts @calcom/Foundation
/packages/trpc/server/routers/viewer/slots/**/* @calcom/Foundation
/packages/ui/**/* @calcom/Consumer @calcom/Foundation
# Exclude test files from requiring foundation/consumer approval
**/*.spec.*
**/*.e2e.*
**/*.e2e-spec.*
**/*.test.*
**/*.test-suite.*
**/*.integration-test.*
-120
View File
@@ -1,120 +0,0 @@
---
name: Companion (iOS/Android/Extension)
about: Report bugs or request features for mobile apps and browser extension
title: ""
labels: ["companion", "🚨 needs approval"]
assignees: ""
---
### Issue Type
<!--
Select one:
- Bug Report
- Feature Request
-->
- [ ] 🐛 Bug Report
- [ ] ✨ Feature Request
### Platform
<!--
Select all that apply:
-->
- [ ] 📱 iOS App
- [ ] 🤖 Android App
- [ ] 🧩 Browser Extension
### Platform Details
<!--
Fill in the details for your selected platform(s).
Delete sections that don't apply.
-->
#### iOS
- **iOS Version**: (e.g., 17.2)
- **Device Model**: (e.g., iPhone 15 Pro)
- **App Version**: (e.g., 1.0.0)
#### Android
- **Android Version**: (e.g., 14)
- **Device Model**: (e.g., Pixel 8)
- **App Version**: (e.g., 1.0.0)
#### Browser Extension
- **Browser & Version**: (e.g., Chrome 120, Firefox 121)
- **Extension Version**: (e.g., 1.0.0)
---
### Description
<!--
Provide a clear and concise description of the issue or feature.
-->
(Write your description here.)
### Steps to Reproduce (Bug Reports Only)
<!--
If this is a bug report, provide steps to reproduce the issue.
Delete this section for feature requests.
-->
1. Go to...
2. Click on...
3. See error...
### Expected Behavior
<!--
What did you expect to happen?
-->
(Describe what you expected.)
### Actual Behavior (Bug Reports Only)
<!--
What actually happened? Delete this section for feature requests.
-->
(Describe what actually happened.)
### Proposed Solution (Feature Requests Only)
<!--
If this is a feature request, describe your proposed solution.
Delete this section for bug reports.
-->
(Describe your proposed solution.)
### Screenshots / Evidence
<!--
Add screenshots, screen recordings, or console logs if applicable.
You can use tools like Bird Eats Bug for recordings.
-->
(Attach evidence here.)
### Additional Context
<!--
Any other information that might be helpful.
-->
(Add any additional context here.)
---
##### House rules
- If this issue has a `🚨 needs approval` label, don't start coding yet. Wait until a core member approves the request by removing this label.
- Your ideas are invaluable! However, they undergo review to ensure alignment with the product's direction.
- Follow best practices in our [Contributor Docs](https://github.com/calcom/cal.com/blob/main/CONTRIBUTING.md)
+8 -1
View File
@@ -7,4 +7,11 @@ GET /v2/bookings/{bookingUid} added 'subschema #3, subschema #6' to the 'data' r
POST /v2/bookings/{bookingUid}/cancel added 'subschema #3, subschema #6' to the 'data' response property 'oneOf' list for the response status '200'
POST /v2/bookings/{bookingUid}/confirm added 'subschema #3, subschema #6' to the 'data' response property 'oneOf' list for the response status '200'
POST /v2/bookings/{bookingUid}/decline added 'subschema #3, subschema #6' to the 'data' response property 'oneOf' list for the response status '200'
POST /v2/bookings/{bookingUid}/guests added 'subschema #3, subschema #6' to the 'data' response property 'oneOf' list for the response status '200'
POST /v2/bookings/{bookingUid}/guests added 'subschema #3, subschema #6' to the 'data' response property 'oneOf' list for the response status '200'
DELETE /v2/event-types/{eventTypeId}/webhooks/{webhookId} added the new path request parameter 'webhookId'
GET /v2/event-types/{eventTypeId}/webhooks/{webhookId} added the new path request parameter 'webhookId'
DELETE /v2/oauth-clients/{clientId}/webhooks/{webhookId} added the new path request parameter 'webhookId'
GET /v2/oauth-clients/{clientId}/webhooks/{webhookId} added the new path request parameter 'webhookId'
DELETE /v2/teams/{teamId}/event-types/{eventTypeId}/webhooks/{webhookId} added the new path request parameter 'webhookId'
GET /v2/teams/{teamId}/event-types/{eventTypeId}/webhooks/{webhookId} added the new path request parameter 'webhookId'
GET /v2/webhooks/{webhookId} added the new path request parameter 'webhookId'
-44
View File
@@ -1,44 +0,0 @@
name: Companion Builds
on:
workflow_call:
permissions:
contents: read
env:
EXPO_PUBLIC_CAL_API_KEY: ${{ secrets.CI_EXPO_PUBLIC_CAL_API_KEY || vars.CI_EXPO_PUBLIC_CAL_API_KEY || vars.EXPO_PUBLIC_CAL_API_KEY }}
jobs:
build:
name: Build Companion App & Extension
runs-on: blacksmith-4vcpu-ubuntu-2404
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
sparse-checkout: .github
- uses: ./.github/actions/cache-checkout
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: 1.3.0
cache: true
cache-dependency-path: companion/bun.lock
- name: Install dependencies
working-directory: companion
run: bun install --frozen-lockfile
- name: Build Expo web app
working-directory: companion
env:
EXPO_NO_TELEMETRY: 1
CI: true
run: bunx expo export --platform web
- name: Build browser extension
working-directory: companion
run: bun run ext:build
-33
View File
@@ -1,33 +0,0 @@
name: Companion Lint
on:
workflow_call:
permissions:
contents: read
jobs:
lint:
name: Lint Companion App
runs-on: blacksmith-2vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
sparse-checkout: .github
- uses: ./.github/actions/cache-checkout
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: 1.3.0
cache: false
- name: Install dependencies
working-directory: companion
run: bun install --frozen-lockfile
- name: Run lint
working-directory: companion
run: bun run lint:all
-34
View File
@@ -1,34 +0,0 @@
name: Companion Type Check
on:
workflow_call:
permissions:
contents: read
jobs:
typecheck:
name: Type Check Companion App
runs-on: blacksmith-2vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
with:
sparse-checkout: .github
- uses: ./.github/actions/cache-checkout
- name: Setup Bun
uses: oven-sh/setup-bun@v1
with:
bun-version: 1.3.0
cache: true
cache-dependency-path: companion/bun.lock
- name: Install dependencies
working-directory: companion
run: bun install --frozen-lockfile
- name: Type check
working-directory: companion
run: bun run typecheck:all
+1 -37
View File
@@ -167,7 +167,6 @@ jobs:
pull-requests: read
outputs:
has-files-requiring-all-checks: ${{ steps.filter-exclusions.outputs.has-files-requiring-all-checks }}
has-companion: ${{ steps.filter-inclusions.outputs.has-companion }}
has-api-v2-changes: ${{ steps.filter-inclusions.outputs.has-api-v2-changes }}
has-prisma-changes: ${{ steps.filter-inclusions.outputs.has-prisma-changes }}
has-agents-changes: ${{ steps.filter-inclusions.outputs.has-agents-changes }}
@@ -197,14 +196,13 @@ jobs:
filters: |
has-files-requiring-all-checks:
- '**'
- '!companion/**'
- '!.vscode/**'
- '!**/*.md'
- '!**/*.mdx'
- '!.github/CODEOWNERS'
- '!docs/**'
- '!help/**'
- '!apps/web/public/static/locales/**/common.json'
- '!packages/i18n/locales/**/common.json'
- '!i18n.lock'
- name: Check for specific path changes
uses: dorny/paths-filter@v3
@@ -213,8 +211,6 @@ jobs:
filters: |
has-agents-changes:
- "agents/**"
has-companion:
- "companion/**"
has-api-v2-changes:
- "apps/api/v2/**"
- "packages/platform-constants/**"
@@ -387,27 +383,6 @@ jobs:
uses: ./.github/workflows/docs-build.yml
secrets: inherit
build-companion:
name: Companion builds
needs: [prepare]
if: needs.prepare.outputs.has-companion == 'true'
uses: ./.github/workflows/companion-build.yml
secrets: inherit
typecheck-companion:
name: Type Checks
needs: [prepare]
if: needs.prepare.outputs.has-companion == 'true'
uses: ./.github/workflows/companion-typecheck.yml
secrets: inherit
lint-companion:
name: Linters
needs: [prepare]
if: needs.prepare.outputs.has-companion == 'true'
uses: ./.github/workflows/companion-lint.yml
secrets: inherit
build:
name: Production builds
needs: [prepare]
@@ -489,9 +464,6 @@ jobs:
build-api-v2,
build-atoms,
build-docs,
build-companion,
typecheck-companion,
lint-companion,
setup-db,
e2e,
e2e-api-v2,
@@ -540,14 +512,6 @@ jobs:
needs.e2e-app-store.result != 'success'
)
) ||
(
needs.prepare.outputs.has-companion == 'true' &&
(
needs.build-companion.result != 'success' ||
needs.typecheck-companion.result != 'success' ||
needs.lint-companion.result != 'success'
)
) ||
(
needs.prepare.outputs.has-agents-changes == 'true' &&
needs.validate-agents-format.result != 'success'
@@ -12,6 +12,7 @@ permissions:
jobs:
sync:
if: false
name: Sync to Devin Knowledge
runs-on: blacksmith-2vcpu-ubuntu-2404
steps:
+3
View File
@@ -108,6 +108,9 @@ packages/**/.yarn/ci-cache/
.claude/plans/
.claude/settings.local.json
# Spec drafts (rough work, not ready for review)
specs/**/_drafts/
# trigger.dev
.trigger
agents/devin-knowledge.json
+6
View File
@@ -4,4 +4,10 @@ enableGlobalCache: false
nodeLinker: node-modules
# fast-xml-parser 4.4.1 via @boxyhq/saml-jackson → @aws-sdk/core@3.816.0 (transitive).
# Only parses trusted AWS API responses, not user input. No practical attack vector.
# Upstream fix pending: ory/polis (saml-jackson) has bumped to @aws-sdk@3.994.0 on main but hasn't released yet.
npmAuditIgnoreAdvisories:
- "1113407"
yarnPath: .yarn/releases/yarn-4.12.0.cjs
+12 -2
View File
@@ -12,11 +12,12 @@ You are a senior Cal.com engineer working in a Yarn/Turbo monorepo. You prioriti
- Create PRs in draft mode by default
- Run `yarn type-check:ci --force` before concluding CI failures are unrelated to your changes
- Import directly from source files, not barrel files (e.g., `@calcom/ui/components/button` not `@calcom/ui`)
- Add translations to `apps/web/public/static/locales/en/common.json` for all UI strings
- Add translations to `packages/i18n/locales/en/common.json` for all UI strings
- Use `date-fns` or native `Date` instead of Day.js when timezone awareness isn't needed
- Put permission checks in `page.tsx`, never in `layout.tsx`
- Use `ast-grep` for searching if available; otherwise use `rg` (ripgrep), then fall back to `grep`
- Use Biome for formatting and linting
- Only add code comments that explain **why**, not **what** — see [code comment guidelines](agents/rules/quality-code-comments.md)
## Don't
@@ -29,6 +30,7 @@ You are a senior Cal.com engineer working in a Yarn/Turbo monorepo. You prioriti
- Never use barrel imports from index.ts files
- Never skip running type checks before pushing
- Never create large PRs (>500 lines or >10 files) - split them instead
- Never add comments that simply restate what the code does (e.g., `// Get the user` above a `getUser()` call)
## PR Size Guidelines
@@ -124,7 +126,7 @@ packages/lib/ # Shared utilities
- Routes: `apps/web/app/` (App Router)
- Database schema: `packages/prisma/schema.prisma`
- tRPC routers: `packages/trpc/server/routers/`
- Translations: `apps/web/public/static/locales/en/common.json`
- Translations: `packages/i18n/locales/en/common.json`
- Workflow constants: `packages/features/ee/workflows/lib/constants.ts`
## Tech Stack
@@ -224,6 +226,14 @@ import { ProfileRepository } from "@calcom/features/profile/repositories/Profile
- Fix type errors before test failures - they're often the root cause
- Run `yarn prisma generate` if you see missing enum/type errors
## Spec-Driven Development (Opt-In)
For complex features, you can use spec-driven development when explicitly requested.
**To enable:** Tell the AI "use spec-driven development" or "follow the spec workflow"
See [SPEC-WORKFLOW.md](SPEC-WORKFLOW.md) for the full workflow documentation.
## Extended Documentation
For detailed information, see the `agents/` directory:
+14 -10
View File
@@ -149,6 +149,13 @@ Here is what you need to be able to run Cal.com.
- Duplicate `.env.example` to `.env`
- Use `openssl rand -base64 32` to generate a key and add it under `NEXTAUTH_SECRET` in the `.env` file.
- Use `openssl rand -base64 24` to generate a key and add it under `CALENDSO_ENCRYPTION_KEY` in the `.env` file.
> **Windows users:** Replace the `packages/prisma/.env` symlink with a real copy to avoid a Prisma error (`unexpected character / in variable name`):
>
> ```sh
> # Git Bash / WSL
> rm packages/prisma/.env && cp .env packages/prisma/.env
> ```
5. Setup Node
If your Node version does not meet the project's requirements as instructed by the docs, "nvm" (Node Version Manager) allows using Node at the version required by the project:
@@ -671,7 +678,7 @@ Certain versions may have trouble creating a user if the field `metadata` is emp
##### CLIENT_FETCH_ERROR
If you experience this error, it may be the way the default Auth callback in the server is using the WEBAPP_URL as a base url. The container does not necessarily have access to the same DNS as your local machine, and therefor needs to be configured to resolve to itself. You may be able to correct this by configuring `NEXTAUTH_URL=http://localhost:3000/api/auth`, to help the backend loop back to itself.
If you experience this error, it may be the way the default Auth callback in the server is using the WEBAPP_URL as a base url. The container does not necessarily have access to the same DNS as your local machine, and therefore needs to be configured to resolve to itself. You may be able to correct this by configuring `NEXTAUTH_URL=http://localhost:3000/api/auth`, to help the backend loop back to itself.
```
docker-calcom-1 | @calcom/web:start: [next-auth][error][CLIENT_FETCH_ERROR]
@@ -767,11 +774,14 @@ Cal.com, Inc. is a commercial open source company, which means some parts of thi
<img width="100%" src="https://repobeats.axiom.co/api/embed/6bfca2f20f39738048b6e70ca205efde46352c3d.svg" />
<!-- CONTRIBUTING -->
## Contributing
We ❤️ contributions! Whether it’s fixing a typo, improving documentation, or building new features, your help makes Cal.com better.
Please see our [contributing guide](/CONTRIBUTING.md).
- Check out our [Contributing Guide](./CONTRIBUTING.md) for detailed steps.
- Join the discussion on [GitHub Discussions](https://github.com/calcom/cal.com/discussions) or our community channels.
- Please follow our coding standards and commit message conventions to keep the project consistent.
Even small improvements matter — thank you for helping us grow!
### Good First Issues
@@ -984,12 +994,6 @@ An example of good readme is [atoms readme](https://github.com/calcom/cal.com/bl
1. Follow semantic versioning when using changesets.
2. Mark breaking changes using `❗️Breaking change`
<!-- LICENSE -->
## License
Distributed under the [AGPLv3 License](https://github.com/calcom/cal.com/blob/main/LICENSE). See `LICENSE` for more information.
<!-- ACKNOWLEDGEMENTS -->
## Acknowledgements
+105
View File
@@ -0,0 +1,105 @@
# Spec-Driven Development Workflow
This workflow is **opt-in**. Use it when explicitly requested by saying "use spec-driven development" or "follow the spec workflow".
## Design Documents
The `specs/` folder contains design documents for features in development.
Each spec follows this structure:
```
specs/{feature}/
├── CLAUDE.md # Feature-specific instructions (read this first)
├── design.md # The specification
├── implementation.md # Current status and what's done
├── decisions.md # Why decisions were made
├── prompts.md # Reusable prompts
├── future-work.md # What's deferred
└── docs/ # Documentation with screenshots
```
**Workflow:**
1. Read the spec's `CLAUDE.md` for specific instructions
2. Read `design.md` to understand what we're building
3. Check `implementation.md` for current status
4. Find the relevant code in the codebase
5. Implement in small pieces, update `implementation.md` after each
---
## When Implementing Features (Spec Mode)
1. **Check for design doc** in `specs/` — if it exists, follow it
2. **If no spec exists** — ask if you should create one first
3. **Look at existing patterns** — find similar code and follow conventions
4. **Update implementation.md** — mark what's done after each piece
5. **Update decisions.md** — when choosing between approaches
---
## Creating a New Spec
When user asks to build a new feature:
1. Copy the template: `cp -r specs/_templates specs/{feature-name}`
2. Explore the codebase to understand existing patterns
3. Write `design.md` with technical spec
4. Write `CLAUDE.md` with feature-specific instructions
5. Initialize `implementation.md` with "not-started" status
6. Ask user to review before implementing
---
## Updating Spec Files
### implementation.md — After completing each piece:
```markdown
## Status: in-progress
## Completed
- [x] Database schema
- [x] Migration file
## In Progress
- tRPC endpoints
## Next Steps
1. UI components
2. Tests
## Session Notes
### 2024-01-15
- Done: Added schema, created migration
- Next: Implement tRPC router
```
### decisions.md — When choosing between approaches:
```markdown
## ADR-001: Use Separate Table for Custom Locations
### Context
Need to store user-defined locations.
### Options
1. JSON field — simpler, but harder to query
2. Separate table — more flexible, better indexing
### Decision
Separate table for better querying.
### Consequences
- Need migration
- Need new tRPC router
```
---
## Don't (When Using Spec-Driven Development)
- Don't implement features without checking for a design doc first
- Don't skip updating implementation.md after completing work
- Don't make architectural decisions without recording them in decisions.md
+1
View File
@@ -65,6 +65,7 @@
- [patterns-factory-pattern](rules/patterns-factory-pattern.md) - Factory pattern
- [patterns-workflow-triggers](rules/patterns-workflow-triggers.md) - Workflow implementation
- [patterns-app-store](rules/patterns-app-store.md) - App store integration patterns
- [patterns-trigger-dev](rules/patterns-trigger-dev.md) - Trigger.dev task implementation
### Culture
@@ -0,0 +1,193 @@
---
title: Prevent Circular Dependencies Between Packages
impact: CRITICAL
impactDescription: Prevents build failures, type errors, ensures honest implementation, and maintains clean dependency graph
tags: architecture, dependencies, packages, imports, circular
---
## Prevent Circular Dependencies Between Packages
**Impact: CRITICAL**
Circular dependencies between packages cause build failures, type errors, and make the codebase unmaintainable. The dependency graph must be acyclic, with clear layers from low-level utilities up to high-level features.
The dependency hierarchy (from lowest to highest):
```
packages/lib (lowest - no feature dependencies)
↓
packages/app-store
↓
packages/features
↓
packages/trpc
↓
apps/web (highest - can depend on all packages)
```
**Benefits:**
- **Honest implementation**: The dependency graph accurately reflects what code depends on what, with no hidden or circular relationships that create false expectations
- **Predictable behavior**: Code behaves as the dependency structure suggests - no surprises from circular imports
- **Clear mental model**: Developers can reason about the system without tracking complex circular relationships
- **Build reliability**: No circular dependency errors during compilation or bundling
- **Easier testing**: Lower-level packages can be tested independently without pulling in the entire codebase
### `packages/lib`
**Rules:**
1. No files in `packages/lib` import from `@calcom/app-store` or `../app-store/**`
2. No files in `packages/lib` import from `@calcom/features` or `../features/**`
3. No files in `packages/lib` import from `@calcom/trpc` or `../trpc/**`
4. No files in `packages/lib` import from `@trpc/server`
5. **BONUS:** No repository files allowed in `packages/lib` (repositories belong in features or app-store)
**Incorrect:**
```typescript
// Bad - lib importing from features
import { getBooking } from "@calcom/features/bookings";
import { EventRepository } from "@calcom/features/events/repositories";
// Bad - lib importing from app-store
import { googleCalendarHandler } from "@calcom/app-store/googlecalendar";
// Bad - lib importing from trpc
import { router } from "@calcom/trpc/server/trpc";
```
**Correct:**
```typescript
// Good - lib only imports from other lib files or external packages
import { logger } from "@calcom/lib/logger";
import { prisma } from "@calcom/prisma";
import type { User } from "@prisma/client";
```
### `packages/app-store`
**Rules:**
6. No files in `packages/app-store` import from `@calcom/features` or `../features/**`
7. No files in `packages/app-store` import from `@calcom/trpc` or `../trpc/**`
**Incorrect:**
```typescript
// Bad - app-store importing from features
import { BookingService } from "@calcom/features/bookings/services";
// Bad - app-store importing from trpc
import { publicProcedure } from "@calcom/trpc/server/trpc";
```
**Correct:**
```typescript
// Good - app-store imports from lib and prisma
import { logger } from "@calcom/lib/logger";
import { prisma } from "@calcom/prisma";
import type { Credential } from "@prisma/client";
```
### `packages/features`
**Rules:**
8. No files in `packages/features` import from `@calcom/trpc` or `../trpc/**`
9. No files in `packages/features` import from `@calcom/web` or `@calcom/web/**`
10. No files in `packages/features` import from `../../apps/web/**`
**Incorrect:**
```typescript
// Bad - features importing from trpc
import { router } from "@calcom/trpc/server/trpc";
// Bad - features importing from web app
import { getServerSession } from "@calcom/web/lib/auth";
import { WebComponent } from "../../apps/web/components/WebComponent";
```
**Correct:**
```typescript
// Good - features import from lib, app-store, and prisma
import { logger } from "@calcom/lib/logger";
import { prisma } from "@calcom/prisma";
import { googleCalendarHandler } from "@calcom/app-store/googlecalendar";
```
### `packages/trpc`
**Rules:**
11. No files in `packages/trpc` import from `../apps/web/**`
**Incorrect:**
```typescript
// Bad - trpc importing from web app
import { getServerSession } from "../../apps/web/lib/auth";
```
**Correct:**
```typescript
// Good - trpc imports from features, lib, and prisma
import { BookingService } from "@calcom/features/bookings/services";
import { logger } from "@calcom/lib/logger";
import { prisma } from "@calcom/prisma";
```
### `packages/testing`
**Rules:**
12. No files in `packages/testing` import from `@calcom/web` or `@calcom/web/**`
13. No files in `packages/testing` import from `@calcom/features` or `@calcom/features/**`
14. No files in `packages/testing` import from `../../apps/web/**`
15. No files in `packages/testing` import from `../features/**`
**Incorrect:**
```typescript
// Bad - testing importing from web or features
import { WebComponent } from "@calcom/web/components";
import { BookingService } from "@calcom/features/bookings";
```
**Correct:**
```typescript
// Good - testing imports from lib and prisma
import { prisma } from "@calcom/prisma";
import { logger } from "@calcom/lib/logger";
```
### `packages/platform/atoms`
**Rules:**
16. No files in `packages/platform/atoms` import from `@calcom/trpc` or `@calcom/trpc/**`
17. No files in `packages/platform/atoms` import from `../../trpc` or `../../trpc/**`
18. No files in `packages/platform/atoms` import from `@calcom/web`
**Incorrect:**
```typescript
// Bad - platform/atoms importing from trpc or web
import { router } from "@calcom/trpc/server/trpc";
import { trpc } from "../../trpc";
import { WebComponent } from "@calcom/web";
```
**Correct:**
```typescript
// Good - platform/atoms imports from lib, features, and ui
import { logger } from "@calcom/lib/logger";
import { Button } from "@calcom/ui/components/button";
import type { Booking } from "@calcom/features/bookings/types";
```
## Enforcement
These rules should be enforced through:
- ESLint rules that detect forbidden import paths
- CI checks that fail on circular dependencies
- Code review guidelines that flag violations
+240
View File
@@ -0,0 +1,240 @@
---
title: Trigger.dev Task Implementation
impact: HIGH
impactDescription: Consistent Trigger.dev patterns ensure reliable async task execution across web and API v2
tags: trigger.dev, async, tasker, concurrency, cron, scheduled-tasks
---
# Trigger.dev Task Implementation
Trigger.dev is the async task runner used in both `apps/web` and `apps/api/v2`. Tasks can be disabled via the `ENABLE_ASYNC_TASKER` env var (set to `"false"` to fall back to synchronous execution).
## Tasker Architecture
Every Trigger.dev feature follows the Tasker pattern with these layers:
```
packages/features/<domain>/lib/tasker/
types.ts # ITasker interface + payload types
<Domain>Tasker.ts # Tasker subclass (dispatches async or sync)
<Domain>TriggerTasker.ts # Async implementation (calls .trigger())
<Domain>SyncTasker.ts # Sync fallback (executes inline)
<Domain>TaskService.ts # Business logic consumed by both
trigger/
config.ts # Queue + retry + machine config
schema.ts # Zod payload schema
<task-name>.ts # schemaTask definition
```
Reference implementation: `packages/features/calendars/lib/tasker/` — see `CalendarsTasker.ts` for the Tasker subclass pattern and `trigger/config.ts` for queue/retry/machine configuration
## Creating a New Task
### 1. Define the Zod schema for payload validation
Always use `schemaTask` with a Zod schema for payload validation:
```typescript
// trigger/schema.ts
import { z } from "zod";
export const myTaskSchema = z.object({
userId: z.number(),
});
```
### 2. Configure queue, retry, and machine
See `packages/features/calendars/lib/tasker/trigger/config.ts` for a real example.
```typescript
// trigger/config.ts
import { type schemaTask, queue } from "@trigger.dev/sdk";
type MyTask = Pick<Parameters<typeof schemaTask>[0], "machine" | "retry" | "queue">;
export const myQueue = queue({
name: "my-domain",
concurrencyLimit: 10,
});
export const myTaskConfig: MyTask = {
machine: "small-2x",
queue: myQueue,
retry: {
maxAttempts: 3,
factor: 2,
minTimeoutInMs: 60000,
maxTimeoutInMs: 300000,
randomize: true,
outOfMemory: {
machine: "medium-1x",
},
},
};
```
### 3. Define the task using schemaTask
```typescript
// trigger/my-task.ts
import { schemaTask, type TaskWithSchema } from "@trigger.dev/sdk";
import type { z } from "zod";
import { myTaskConfig } from "./config";
import { myTaskSchema } from "./schema";
export const MY_TASK_JOB_ID = "domain.my-task";
export const myTask: TaskWithSchema<typeof MY_TASK_JOB_ID, typeof myTaskSchema> =
schemaTask({
id: MY_TASK_JOB_ID,
...myTaskConfig,
schema: myTaskSchema,
run: async (payload: z.infer<typeof myTaskSchema>) => {
const { getMyService } = await import("@calcom/features/<domain>/di/<container>");
const service = getMyService();
await service.execute(payload);
},
});
```
### 4. For scheduled (cron) tasks, use `schedules.task`
```typescript
import { schedules } from "@trigger.dev/sdk";
export const myScheduledTask = schedules.task({
id: "domain.my-scheduled-task",
...myTaskConfig,
cron: {
pattern: "0 0 1 * *",
timezone: "UTC",
},
run: async (payload) => {
// task logic
},
});
```
Reference: [Trigger.dev Scheduled Tasks](https://trigger.dev/docs/tasks/scheduled)
## Concurrency Configuration
Concurrency limits control how many task runs execute in parallel within a queue. Getting this right is critical for production stability.
**How to estimate concurrency:**
1. Analyze production logs for the number of requests per minute that will trigger the task (from both `apps/web` and `apps/api/v2`)
2. Measure the average execution time of the task
3. Factor in burst patterns (e.g., peak booking hours)
**Guidelines:**
- Time-sensitive tasks (emails, webhooks) need higher concurrency
- Background jobs that are not time-sensitive can use lower concurrency
- Start conservative and increase based on production metrics
See `packages/features/calendars/lib/tasker/trigger/config.ts` (`concurrencyLimit: 10`) and `packages/features/webhooks/lib/tasker/trigger/config.ts` (`concurrencyLimit: 20`) for real examples of how concurrency is tuned per domain.
Reference: [Trigger.dev Concurrency & Queues](https://trigger.dev/docs/queue-concurrency)
## Local Development
1. Set env vars:
```
TRIGGER_SECRET_KEY=<your-trigger-secret>
TRIGGER_API_URL=https://api.trigger.dev
ENABLE_ASYNC_TASKER="true"
```
2. Run the Trigger.dev CLI from the features package:
```bash
cd packages/features && npx trigger.dev@latest dev --analyze
```
3. Keep the CLI running while developing. Tasks appear in the Trigger.dev dashboard under **Tasks**.
## Before Merging
1. **Deploy to staging**: `cd packages/features && yarn deploy:trigger:staging`
2. **Test on Trigger.dev dashboard**: Switch to staging environment and use the **Test** tab
3. **Right-size machines**: Start with the smallest machine; increase only if you see `OutOfMemory` errors
4. **Set retry with OOM handling**: Always include `outOfMemory` in retry config with a larger machine than the default
5. **Set concurrency**: Analyze production request volume and task completion time to determine the appropriate `concurrencyLimit`
6. **Cherry-pick caveat**: Cherry-picking does not redeploy Trigger.dev tasks. Only the `draft-release` CI action does. If cherry-picking a change that impacts Trigger.dev tasks, manually promote the new version in the Trigger.dev deployment dashboard after the fix is deployed
## Common Mistakes
**Using `task` instead of `schemaTask`:**
```typescript
// Bad - no payload validation
import { task } from "@trigger.dev/sdk";
export const myTask = task({
id: "my-task",
run: async (payload: any) => { ... },
});
// Good - validated payload with Zod
import { schemaTask } from "@trigger.dev/sdk";
export const myTask = schemaTask({
id: "my-task",
schema: myTaskSchema,
run: async (payload) => { ... },
});
```
**Missing retry or queue config:**
```typescript
// Bad - no retry or queue, will use defaults
export const myTask = schemaTask({
id: "my-task",
schema: myTaskSchema,
run: async (payload) => { ... },
});
// Good - explicit config from shared config file
import { myTaskConfig } from "./config";
export const myTask = schemaTask({
id: "my-task",
...myTaskConfig,
schema: myTaskSchema,
run: async (payload) => { ... },
});
```
**Importing eagerly inside task files instead of using dynamic imports:**
```typescript
// Bad - eager import of heavy modules at file scope
import { MyService } from "@calcom/features/domain/service/MyService";
export const myTask = schemaTask({
id: "my-task",
schema: myTaskSchema,
run: async (payload) => {
const service = new MyService();
await service.execute(payload);
},
});
// Good - dynamic import inside run function
export const myTask = schemaTask({
id: "my-task",
schema: myTaskSchema,
run: async (payload) => {
const { getMyService } = await import("@calcom/features/domain/di/container");
const service = getMyService();
await service.execute(payload);
},
});
```
## Key References
- Trigger.dev docs: [Concurrency & Queues](https://trigger.dev/docs/queue-concurrency), [Scheduled Tasks](https://trigger.dev/docs/tasks/scheduled), [schemaTask](https://trigger.dev/docs/tasks/schemaTask)
- Example taskers in the codebase:
- `packages/features/calendars/lib/tasker/` (standard pattern)
- `packages/features/webhooks/lib/tasker/` (webhook delivery)
- `packages/features/ee/billing/service/proration/tasker/` (scheduled cron task)
+4 -1
View File
@@ -13,10 +13,13 @@ Keep comments limited and avoid obvious ones. Comments should explain "why" not
## When to Comment
- Complex business logic that isn't obvious from the code
- Business decisions or domain logic that isn't obvious from the code
- Workarounds or hacks with explanation of why they're needed
- Non-obvious performance optimizations
- Important security considerations
- Troubleshooting context (e.g., why a particular approach was chosen after hitting issues)
If none of these apply, skip the comment entirely. The function name, parameters, and return type should speak for themselves.
## When NOT to Comment
+1 -1
View File
@@ -33,7 +33,7 @@ tags: reference, navigation, file-locations
## Translations
- English: `apps/web/public/static/locales/en/common.json`
- English: `packages/i18n/locales/en/common.json`
## App Store
+22
View File
@@ -1,6 +1,19 @@
---
name: calcom-api
description: Interact with the Cal.com API v2 to manage scheduling, bookings, event types, availability, and calendars. Use this skill when building integrations that need to create or manage bookings, check availability, configure event types, or sync calendars with Cal.com's scheduling infrastructure.
env:
CAL_API_KEY:
description: "Cal.com API key (prefixed with cal_live_ or cal_test_). Required for all API requests."
required: true
CAL_CLIENT_ID:
description: "OAuth client ID for platform integrations managing users on behalf of others. Sent as x-cal-client-id header."
required: false
CAL_SECRET_KEY:
description: "OAuth client secret for platform integrations. Sent as x-cal-secret-key header."
required: false
CAL_WEBHOOK_SECRET:
description: "Secret used to verify webhook payload signatures via X-Cal-Signature-256 header."
required: false
---
# Cal.com API v2
@@ -14,6 +27,15 @@ All API requests should be made to:
https://api.cal.com/v2
```
## Required Credentials
| Environment Variable | Required | Description |
|---------------------|----------|-------------|
| `CAL_API_KEY` | Yes | Cal.com API key (prefixed with `cal_live_` or `cal_test_`). Used as Bearer token for all API requests. Generate from Settings > Developer > API Keys. |
| `CAL_CLIENT_ID` | No | OAuth client ID for platform integrations that manage users on behalf of others. Sent as `x-cal-client-id` header. |
| `CAL_SECRET_KEY` | No | OAuth client secret for platform integrations. Sent as `x-cal-secret-key` header. |
| `CAL_WEBHOOK_SECRET` | No | Secret for verifying webhook payload signatures via the `X-Cal-Signature-256` header. |
## Authentication
All API requests require authentication via Bearer token:
-10
View File
@@ -1,10 +0,0 @@
const path = require("node:path");
const i18nConfig = require("@calcom/config/next-i18next.config");
/** @type {import("next-i18next").UserConfig} */
const config = {
...i18nConfig,
localePath: path.resolve("../../web/public/static/locales"),
};
module.exports = config;
@@ -82,6 +82,7 @@ async function handler(req: NextApiRequest) {
return await handleCancelBooking({
bookingData: { id, allRemainingBookings, cancellationReason, cancelledBy },
userId: req.userId,
actionSource: "API_V1",
});
}
@@ -1,7 +1,7 @@
import type { NextApiRequest } from "next";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
@@ -1,7 +1,7 @@
import type { NextApiRequest } from "next";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { schemaSelectedCalendarPublic, selectedCalendarIdSchema } from "~/lib/validations/selected-calendar";
@@ -2,8 +2,8 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import type { UpdateArguments } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import type { UpdateArguments } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
@@ -2,8 +2,8 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import type { FindManyArgs } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import type { FindManyArgs } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import { schemaSelectedCalendarPublic } from "~/lib/validations/selected-calendar";
import { schemaQuerySingleOrMultipleUserIds } from "~/lib/validations/shared/queryUserId";
@@ -2,7 +2,7 @@ import type { NextApiRequest } from "next";
import { HttpError } from "@calcom/lib/http-error";
import { defaultResponder } from "@calcom/lib/server/defaultResponder";
import { SelectedCalendarRepository } from "@calcom/lib/server/repository/selectedCalendar";
import { SelectedCalendarRepository } from "@calcom/features/selectedCalendar/repositories/SelectedCalendarRepository";
import prisma from "@calcom/prisma";
import type { Prisma } from "@calcom/prisma/client";
+1 -2
View File
@@ -1,4 +1,3 @@
// TODO: Fix tests (These test were never running due to the vitest workspace config)
import prismaMock from "@calcom/testing/lib/__mocks__/prismaMock";
import type { Request, Response } from "express";
@@ -174,7 +173,7 @@ vi.mock("@calcom/features/ee/workflows/lib/getAllWorkflowsFromEventType", () =>
getAllWorkflowsFromEventType: vi.fn().mockResolvedValue([]),
}));
vi.mock("@calcom/lib/server/i18n", () => {
vi.mock("@calcom/i18n/server", () => {
const mockT = (key: string, options?: any) => {
if (key === "event_between_users") {
return `${options?.eventName} between ${options?.host} and ${options?.attendeeName}`;
+1 -1
View File
@@ -14,7 +14,7 @@ import handler from "../../../pages/api/users/_post";
type CustomNextApiRequest = NextApiRequest & Request;
type CustomNextApiResponse = NextApiResponse & Response;
vi.mock("@calcom/lib/server/i18n", () => {
vi.mock("@calcom/i18n/server", () => {
return {
getTranslation: (key: string) => {
return () => key;
+1 -1
View File
@@ -1 +1 @@
export const TRIGGER_VERSION = '20260205.1';
export const TRIGGER_VERSION = '20260216.1';
+1 -1
View File
@@ -27,7 +27,7 @@ CALENDSO_ENCRYPTION_KEY="Lmqy57DlHKPvwwrtkwjL/8QtxJWxC/OV"
# Service Account Encryption Key for encrypting/decrypting service account keys
CALCOM_SERVICE_ACCOUNT_ENCRYPTION_KEY="LDBFYLEVICRZBYQZUZCSTZRJFZUKZMEI"
# url to redis instance running in Docker and used to cache data. Redis is setup in apps/api/v2/docker-compose.yaml
REDIS_URL="rediss://localhost:6379"
REDIS_URL="redis://localhost:6379"
# KEEP THIS EMPTY, DISABLE SENTRY CLIENT INSIDE OF LIBRARIES USED BY APIv2
NEXT_PUBLIC_SENTRY_DSN=
-11
View File
@@ -1,11 +0,0 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require("node:path");
const i18nConfig = require("@calcom/config/next-i18next.config");
/** @type {import("next-i18next").UserConfig} */
const config = {
...i18nConfig,
localePath: path.resolve("../../web/public/static/locales"),
};
module.exports = config;
+1 -1
View File
@@ -62,7 +62,7 @@
"@sentry/node": "9.46.0",
"@sentry/profiling-node": "9.46.0",
"@snyk/protect": "latest",
"axios": "1.13.2",
"axios": "1.13.5",
"body-parser": "1.20.3",
"bull": "4.15.1",
"class-transformer": "0.5.1",
+12
View File
@@ -13,6 +13,7 @@ import { RedirectsMiddleware } from "@/middleware/app.redirects.middleware";
import { RewriterMiddleware } from "@/middleware/app.rewrites.middleware";
import { JsonBodyMiddleware } from "@/middleware/body/json.body.middleware";
import { RawBodyMiddleware } from "@/middleware/body/raw.body.middleware";
import { UrlencodedBodyMiddleware } from "@/middleware/body/urlencoded.body.middleware";
import { ResponseInterceptor } from "@/middleware/request-ids/request-id.interceptor";
import { RequestIdMiddleware } from "@/middleware/request-ids/request-id.middleware";
import { AuthModule } from "@/modules/auth/auth.module";
@@ -100,6 +101,17 @@ export class AppModule implements NestModule {
method: RequestMethod.POST,
}
)
.apply(UrlencodedBodyMiddleware)
.forRoutes(
{
path: "/v2/auth/oauth2/token",
method: RequestMethod.POST,
},
{
path: "/api/v2/auth/oauth2/token",
method: RequestMethod.POST,
}
)
.apply(JsonBodyMiddleware)
.forRoutes("*")
.apply(RequestIdMiddleware)
@@ -14,7 +14,7 @@ import {
handleCancelBooking,
handleMarkNoShow,
} from "@calcom/platform-libraries";
import { type InstantBookingCreateResult } from "@calcom/platform-libraries/bookings";
import { type InstantBookingCreateResult, makeUserActor } from "@calcom/platform-libraries/bookings";
import { ErrorCode, HttpError } from "@calcom/platform-libraries/errors";
import type { ApiResponse } from "@calcom/platform-types";
import {
@@ -279,6 +279,7 @@ export class BookingsController_2024_04_15 {
platformCancelUrl: bookingRequest.platformCancelUrl,
platformRescheduleUrl: bookingRequest.platformRescheduleUrl,
platformBookingUrl: bookingRequest.platformBookingUrl,
actionSource: "API_V2",
});
if (!res.onlyRemovedAttendee && res.isPlatformManagedUserBooking) {
void (await this.billingService.cancelUsageByBookingUid(res.bookingUid));
@@ -314,7 +315,8 @@ export class BookingsController_2024_04_15 {
attendees: body.attendees,
noShowHost: body.noShowHost,
userId: user.id,
userUuid: user.uuid,
actor: makeUserActor(user.uuid),
actionSource: "API_V2",
});
return { status: SUCCESS_STATUS, data: markNoShowResponse };
@@ -610,6 +612,10 @@ export class BookingsController_2024_04_15 {
...clone.body,
noEmail: oAuthParams === undefined ? false : !oAuthParams.arePlatformEmailsEnabled,
creationSource: CreationSource.API_V2,
metadata: {
...(clone.body.metadata || {}),
...(oAuthClientId && { platformClientId: oAuthClientId }),
},
};
if (oAuthClientId) {
await this.setPlatformAttendeesEmails(clone.body, oAuthClientId);
@@ -1,9 +1,12 @@
import { Module } from "@nestjs/common";
import { BookingAttendeesController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-attendees.controller";
import { BookingGuestsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-guests.controller";
import { BookingLocationController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/booking-location.controller";
import { BookingsController_2024_08_13 } from "@/ee/bookings/2024-08-13/controllers/bookings.controller";
import { BookingPbacGuard } from "@/ee/bookings/2024-08-13/guards/booking-pbac.guard";
import { BookingReferencesRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/booking-references.repository";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
import { BookingAttendeesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-attendees.service";
import { BookingGuestsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-guests.service";
import { BookingLocationService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-location.service";
import { BookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-references.service";
@@ -12,20 +15,22 @@ import { CalVideoOutputService } from "@/ee/bookings/2024-08-13/services/cal-vid
import { CalVideoService } from "@/ee/bookings/2024-08-13/services/cal-video.service";
import { ErrorsBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/errors.service";
import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service";
import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service";
import { OutputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output.service";
import { OutputBookingReferencesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/output-booking-references.service";
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
import { CalendarsRepository } from "@/ee/calendars/calendars.repository";
import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service";
import { CalendarsService } from "@/ee/calendars/services/calendars.service";
import { CalendarsCacheService } from "@/ee/calendars/services/calendars-cache.service";
import { EventTypesModule_2024_04_15 } from "@/ee/event-types/event-types_2024_04_15/event-types.module";
import { EventTypesModule_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.module";
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
import { OutputEventTypesService_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/services/output-event-types.service";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.module";
import { InstantBookingModule } from "@/lib/modules/instant-booking.module";
import { RecurringBookingModule } from "@/lib/modules/recurring-booking.module";
import { RegularBookingModule } from "@/lib/modules/regular-booking.module";
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
import { ApiKeysRepository } from "@/modules/api-keys/api-keys-repository";
import { AppsRepository } from "@/modules/apps/apps.repository";
import { BillingModule } from "@/modules/billing/billing.module";
@@ -49,8 +54,6 @@ import { TeamsModule } from "@/modules/teams/teams/teams.module";
import { TokensModule } from "@/modules/tokens/tokens.module";
import { TokensRepository } from "@/modules/tokens/tokens.repository";
import { UsersModule } from "@/modules/users/users.module";
import { Module } from "@nestjs/common";
import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.module";
@Module({
imports: [
@@ -80,6 +83,7 @@ import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.m
OAuthClientRepository,
OAuthClientUsersService,
BookingsService_2024_08_13,
BookingAttendeesService_2024_08_13,
BookingGuestsService_2024_08_13,
InputBookingsService_2024_08_13,
OutputBookingsService_2024_08_13,
@@ -105,9 +109,11 @@ import { BookingEventHandlerModule } from "@/lib/modules/booking-event-handler.m
CalVideoOutputService,
BookingPbacGuard,
BookingLocationService_2024_08_13,
PrismaFeaturesRepository,
],
controllers: [
BookingsController_2024_08_13,
BookingAttendeesController_2024_08_13,
BookingGuestsController_2024_08_13,
BookingLocationController_2024_08_13,
],
@@ -0,0 +1,71 @@
import { BOOKING_WRITE, SUCCESS_STATUS } from "@calcom/platform-constants";
import { AddAttendeeInput_2024_08_13 } from "@calcom/platform-types";
import { Body, Controller, HttpCode, HttpStatus, Param, Post, UseGuards } from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { BookingPbacGuard } from "@/ee/bookings/2024-08-13/guards/booking-pbac.guard";
import { BookingUidGuard } from "@/ee/bookings/2024-08-13/guards/booking-uid.guard";
import { AddAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output";
import { BookingAttendeesService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/booking-attendees.service";
import { VERSION_2024_08_13, VERSION_2024_08_13_VALUE } from "@/lib/api-versions";
import { API_KEY_OR_ACCESS_TOKEN_HEADER } from "@/lib/docs/headers";
import { Throttle } from "@/lib/endpoint-throttler-decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { Permissions } from "@/modules/auth/decorators/permissions/permissions.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
@Controller({
path: "/v2/bookings/:bookingUid/attendees",
version: VERSION_2024_08_13_VALUE,
})
@UseGuards(PermissionsGuard)
@DocsTags("Bookings / Attendees")
@ApiHeader({
name: "cal-api-version",
description: `Must be set to ${VERSION_2024_08_13}. This header is required as this endpoint does not exist in older API versions.`,
example: VERSION_2024_08_13,
required: true,
})
export class BookingAttendeesController_2024_08_13 {
constructor(private readonly bookingAttendeesService: BookingAttendeesService_2024_08_13) {}
@Post("/")
@HttpCode(HttpStatus.CREATED)
@Permissions([BOOKING_WRITE])
@UseGuards(ApiAuthGuard, BookingUidGuard, BookingPbacGuard)
@Throttle({
limit: 5,
ttl: 60000,
blockDuration: 60000,
name: "booking_attendees_add",
})
@ApiHeader(API_KEY_OR_ACCESS_TOKEN_HEADER)
@ApiOperation({
summary: "Add an attendee to a booking",
description: `Add a new attendee to an existing booking by its UID.
**Side effects:**
- The booking's attendee list is updated in the database
- The calendar event is updated on connected calendars (Google Calendar, Outlook, etc.) to include the new attendee
- An email notification is sent to the new attendee with the booking details
**Permissions:**
- The authenticated user must be either the booking organizer, an existing attendee, or have the \`booking.update\` permission for the team
<Note>The cal-api-version header is required for this endpoint. Without it, the request will fail with a 404 error.</Note>
`,
})
async addAttendee(
@Param("bookingUid") bookingUid: string,
@Body() body: AddAttendeeInput_2024_08_13,
@GetUser() user: ApiAuthGuardUser
): Promise<AddAttendeeOutput_2024_08_13> {
const attendee = await this.bookingAttendeesService.addAttendee(bookingUid, body, user);
return {
status: SUCCESS_STATUS,
data: attendee,
};
}
}
@@ -0,0 +1,415 @@
import { CAL_API_VERSION_HEADER, SUCCESS_STATUS, VERSION_2024_08_13 } from "@calcom/platform-constants";
import {
AttendeeAddGuestsEmail,
AttendeeScheduledEmail,
OrganizerAddGuestsEmail,
} from "@calcom/platform-libraries/emails";
import type { BookingOutput_2024_08_13, CreateBookingInput_2024_08_13 } from "@calcom/platform-types";
import type { Team, User } from "@calcom/prisma/client";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test } from "@nestjs/testing";
import request from "supertest";
import { BookingsRepositoryFixture } from "test/fixtures/repository/bookings.repository.fixture";
import { EventTypesRepositoryFixture } from "test/fixtures/repository/event-types.repository.fixture";
import { OAuthClientRepositoryFixture } from "test/fixtures/repository/oauth-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
import { TokensRepositoryFixture } from "test/fixtures/repository/tokens.repository.fixture";
import { UserRepositoryFixture } from "test/fixtures/repository/users.repository.fixture";
import { randomString } from "test/utils/randomString";
import { mockThrottlerGuard } from "test/utils/withNoThrottler";
import { AppModule } from "@/app.module";
import { bootstrap } from "@/bootstrap";
import { AddAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output";
import { CreateBookingOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/create-booking.output";
import { CreateScheduleInput_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/inputs/create-schedule.input";
import { SchedulesModule_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/schedules.module";
import { SchedulesService_2024_04_15 } from "@/ee/schedules/schedules_2024_04_15/services/schedules.service";
import { PermissionsGuard } from "@/modules/auth/guards/permissions/permissions.guard";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
const attendeeAddGuestsEmailSpy = jest
.spyOn(AttendeeAddGuestsEmail.prototype, "getHtml")
.mockImplementation(() => Promise.resolve("<p>email</p>"));
const organizerAddGuestsEmailSpy = jest
.spyOn(OrganizerAddGuestsEmail.prototype, "getHtml")
.mockImplementation(() => Promise.resolve("<p>email</p>"));
const attendeeScheduledEmailSpy = jest
.spyOn(AttendeeScheduledEmail.prototype, "getHtml")
.mockImplementation(() => Promise.resolve("<p>email</p>"));
type TestUser = {
user: User;
accessToken: string;
refreshToken: string;
};
type TestSetup = {
organizer: TestUser;
unrelatedUser: TestUser;
eventTypeId: number;
bookingUid: string;
bookingId: number;
};
describe("Bookings Endpoints 2024-08-13 add attendee", () => {
let app: INestApplication;
let organization: Team;
let userRepositoryFixture: UserRepositoryFixture;
let bookingsRepositoryFixture: BookingsRepositoryFixture;
let schedulesService: SchedulesService_2024_04_15;
let eventTypesRepositoryFixture: EventTypesRepositoryFixture;
let oauthClientRepositoryFixture: OAuthClientRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let tokensRepositoryFixture: TokensRepositoryFixture;
let testSetup: TestSetup;
beforeAll(async () => {
mockThrottlerGuard();
const moduleRef = await Test.createTestingModule({
imports: [AppModule, PrismaModule, UsersModule, SchedulesModule_2024_04_15],
})
.overrideGuard(PermissionsGuard)
.useValue({
canActivate: () => true,
})
.compile();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
bookingsRepositoryFixture = new BookingsRepositoryFixture(moduleRef);
eventTypesRepositoryFixture = new EventTypesRepositoryFixture(moduleRef);
oauthClientRepositoryFixture = new OAuthClientRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
schedulesService = moduleRef.get<SchedulesService_2024_04_15>(SchedulesService_2024_04_15);
tokensRepositoryFixture = new TokensRepositoryFixture(moduleRef);
organization = await teamRepositoryFixture.create({
name: `add-attendee-2024-08-13-organization-${randomString()}`,
});
await setupTestData();
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
});
async function setupTestData() {
const oAuthClient = await createOAuthClient(organization.id, true);
const organizerUser = await userRepositoryFixture.create({
email: `add-attendee-2024-08-13-organizer-${randomString()}@api.com`,
platformOAuthClients: {
connect: { id: oAuthClient.id },
},
});
const unrelatedUserData = await userRepositoryFixture.create({
email: `add-attendee-2024-08-13-unrelated-${randomString()}@api.com`,
platformOAuthClients: {
connect: { id: oAuthClient.id },
},
});
const organizerTokens = await tokensRepositoryFixture.createTokens(organizerUser.id, oAuthClient.id);
const unrelatedUserTokens = await tokensRepositoryFixture.createTokens(
unrelatedUserData.id,
oAuthClient.id
);
const schedule: CreateScheduleInput_2024_04_15 = {
name: `add-attendee-2024-08-13-schedule-${randomString()}`,
timeZone: "Europe/Rome",
isDefault: true,
};
await schedulesService.createUserSchedule(organizerUser.id, schedule);
const eventType = await eventTypesRepositoryFixture.create(
{
title: `add-attendee-2024-08-13-event-type-${randomString()}`,
slug: `add-attendee-2024-08-13-event-type-${randomString()}`,
length: 60,
},
organizerUser.id
);
testSetup = {
organizer: {
user: organizerUser,
accessToken: organizerTokens.accessToken,
refreshToken: organizerTokens.refreshToken,
},
unrelatedUser: {
user: unrelatedUserData,
accessToken: unrelatedUserTokens.accessToken,
refreshToken: unrelatedUserTokens.refreshToken,
},
eventTypeId: eventType.id,
bookingUid: "",
bookingId: 0,
};
}
async function createOAuthClient(organizationId: number, emailsEnabled: boolean) {
const data = {
logo: "logo-url",
name: "name",
redirectUris: ["http://localhost:5555"],
permissions: 32,
areEmailsEnabled: emailsEnabled,
};
const secret = "secret";
const client = await oauthClientRepositoryFixture.create(organizationId, data, secret);
return client;
}
beforeEach(async () => {
attendeeAddGuestsEmailSpy.mockClear();
organizerAddGuestsEmailSpy.mockClear();
attendeeScheduledEmailSpy.mockClear();
});
describe("POST /v2/bookings/:bookingUid/attendees", () => {
beforeAll(async () => {
const createBookingBody: CreateBookingInput_2024_08_13 = {
start: new Date(Date.UTC(2030, 0, 10, 13, 0, 0)).toISOString(),
eventTypeId: testSetup.eventTypeId,
attendee: {
name: "Original Attendee",
email: "original.attendee@gmail.com",
timeZone: "Europe/Rome",
language: "it",
},
location: "https://meet.google.com/abc-def-ghi",
bookingFieldsResponses: {
customField: "customValue",
},
metadata: {
userId: "100",
},
};
const createBookingResponse = await request(app.getHttpServer())
.post("/v2/bookings")
.send(createBookingBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.expect(201);
const createBookingResponseBody: CreateBookingOutput_2024_08_13 = createBookingResponse.body;
expect(createBookingResponseBody.status).toEqual(SUCCESS_STATUS);
if (!responseDataIsBooking(createBookingResponseBody.data)) {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
);
}
testSetup.bookingUid = createBookingResponseBody.data.uid;
testSetup.bookingId = createBookingResponseBody.data.id;
});
describe("Authentication", () => {
it("should return 401 when adding attendee without authentication", async () => {
const addAttendeeBody = {
email: "unauthenticated.attendee@example.com",
name: "Unauthenticated Attendee",
timeZone: "Europe/London",
};
const response = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13);
expect(response.status).toBe(401);
});
});
describe("Authorization", () => {
it("should allow booking organizer to add an attendee", async () => {
const addAttendeeBody = {
email: "new.attendee@example.com",
name: "New Attendee",
timeZone: "Europe/London",
};
const response = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(201);
const responseBody: AddAttendeeOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(responseBody.data.email).toEqual(addAttendeeBody.email);
expect(responseBody.data.name).toEqual(addAttendeeBody.name);
expect(responseBody.data.timeZone).toEqual(addAttendeeBody.timeZone);
expect(responseBody.data.bookingId).toEqual(testSetup.bookingId);
expect(responseBody.data.id).toBeDefined();
});
it("should return 403 when unrelated user tries to add attendee", async () => {
const addAttendeeBody = {
email: "unauthorized.attendee@example.com",
name: "Unauthorized Attendee",
timeZone: "America/New_York",
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.unrelatedUser.accessToken}`)
.expect(403);
});
});
describe("Response format", () => {
it("should return attendee with correct structure", async () => {
const addAttendeeBody = {
email: "structure.test@example.com",
name: "Structure Test Attendee",
timeZone: "Asia/Tokyo",
};
const response = await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(201);
const responseBody: AddAttendeeOutput_2024_08_13 = response.body;
expect(responseBody).toHaveProperty("status", SUCCESS_STATUS);
expect(responseBody).toHaveProperty("data");
expect(responseBody.data).toHaveProperty("id");
expect(responseBody.data).toHaveProperty("bookingId");
expect(responseBody.data).toHaveProperty("name");
expect(responseBody.data).toHaveProperty("email");
expect(responseBody.data).toHaveProperty("timeZone");
expect(typeof responseBody.data.id).toBe("number");
expect(typeof responseBody.data.bookingId).toBe("number");
expect(typeof responseBody.data.name).toBe("string");
expect(typeof responseBody.data.email).toBe("string");
expect(typeof responseBody.data.timeZone).toBe("string");
});
});
describe("Validation", () => {
it("should return 400 when email is missing", async () => {
const addAttendeeBody = {
name: "No Email Attendee",
timeZone: "Europe/London",
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(400);
});
it("should return 400 when email is invalid", async () => {
const addAttendeeBody = {
email: "invalid-email",
name: "Invalid Email Attendee",
timeZone: "Europe/London",
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(400);
});
it("should return 400 when name is missing", async () => {
const addAttendeeBody = {
email: "no.name@example.com",
timeZone: "Europe/London",
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(400);
});
it("should return 400 when timeZone is missing", async () => {
const addAttendeeBody = {
email: "no.timezone@example.com",
name: "No TimeZone Attendee",
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(400);
});
it("should return 400 when timeZone is invalid", async () => {
const addAttendeeBody = {
email: "invalid.timezone@example.com",
name: "Invalid TimeZone Attendee",
timeZone: "Invalid/TimeZone",
};
await request(app.getHttpServer())
.post(`/v2/bookings/${testSetup.bookingUid}/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(400);
});
it("should return 403 when booking does not exist", async () => {
const addAttendeeBody = {
email: "nonexistent.booking@example.com",
name: "Nonexistent Booking Attendee",
timeZone: "Europe/London",
};
await request(app.getHttpServer())
.post(`/v2/bookings/non-existent-booking-uid/attendees`)
.send(addAttendeeBody)
.set(CAL_API_VERSION_HEADER, VERSION_2024_08_13)
.set("Authorization", `Bearer ${testSetup.organizer.accessToken}`)
.expect(403);
});
});
});
afterAll(async () => {
await teamRepositoryFixture.delete(organization.id);
await userRepositoryFixture.deleteByEmail(testSetup.organizer.user.email);
await userRepositoryFixture.deleteByEmail(testSetup.unrelatedUser.user.email);
await bookingsRepositoryFixture.deleteAllBookings(
testSetup.organizer.user.id,
testSetup.organizer.user.email
);
await app.close();
});
function responseDataIsBooking(data: unknown): data is BookingOutput_2024_08_13 {
return !Array.isArray(data) && typeof data === "object" && data !== null && "id" in data;
}
});
@@ -1053,7 +1053,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
.set("Authorization", `Bearer ${apiKeyString}`)
.expect(400);
expect(response.body.message).toEqual("Cancellation reason is required when you are the host");
expect(response.body.message).toEqual("Cancellation reason is required");
});
it("should cancel seated booking", async () => {
@@ -515,7 +515,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(updatedAtDate?.getTime()).toBeGreaterThanOrEqual(beforeCreate.getTime());
expect(updatedAtDate?.getTime()).toBeLessThanOrEqual(afterCreate.getTime());
expect(data.metadata).toEqual(body.metadata);
expect(data.metadata).toEqual({...body.metadata, platformClientId: oAuthClient.id});
createdBooking = data;
} else {
throw new Error(
@@ -2115,7 +2115,7 @@ describe("Bookings Endpoints 2024-08-13", () => {
expect(updatedAtDate?.getTime()).toBeGreaterThanOrEqual(beforeCreate.getTime());
expect(updatedAtDate?.getTime()).toBeLessThanOrEqual(afterCreate.getTime());
expect(data.metadata).toEqual(body.metadata);
expect(data.metadata).toEqual({...body.metadata, platformClientId: oAuthClient.id});
createdBooking = data;
} else {
throw new Error(
@@ -2662,16 +2662,22 @@ describe("Bookings Endpoints 2024-08-13", () => {
});
describe("calendar events", () => {
// Type assertion to access private methods for test spying
const eventManagerProto = EventManager.prototype as unknown as Record<
"createAllCalendarEvents" | "createAllCRMEvents",
(...args: unknown[]) => Promise<unknown[]>
>;
beforeEach(() => {
jest.restoreAllMocks();
jest
.spyOn(EventManager.prototype, "create")
.mockImplementation(() => Promise.resolve({ results: [], referencesToCreate: [] }));
jest
.spyOn(EventManager.prototype, "createAllCalendarEvents")
.spyOn(eventManagerProto, "createAllCalendarEvents")
.mockImplementation(() => Promise.resolve([]));
jest
.spyOn(EventManager.prototype, "createAllCRMEvents")
.spyOn(eventManagerProto, "createAllCRMEvents")
.mockImplementation(() => Promise.resolve([]));
});
@@ -2843,8 +2849,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(EventManager.prototype.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(EventManager.prototype.createAllCRMEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCRMEvents).toHaveBeenCalledTimes(0);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
@@ -2874,8 +2880,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
const responseBody: CreateBookingOutput_2024_08_13 = response.body;
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data).toBeDefined();
expect(EventManager.prototype.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(EventManager.prototype.createAllCRMEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCRMEvents).toHaveBeenCalledTimes(0);
});
});
@@ -2909,8 +2915,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(EventManager.prototype.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(EventManager.prototype.createAllCRMEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCRMEvents).toHaveBeenCalledTimes(0);
bookingThatRequiresConfirmationUid = data.uid;
} else {
throw new Error(
@@ -2935,8 +2941,8 @@ describe("Bookings Endpoints 2024-08-13", () => {
const data: BookingOutput_2024_08_13 = responseBody.data;
expect(data.id).toBeDefined();
expect(data.uid).toBeDefined();
expect(EventManager.prototype.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(EventManager.prototype.createAllCRMEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCalendarEvents).toHaveBeenCalledTimes(0);
expect(eventManagerProto.createAllCRMEvents).toHaveBeenCalledTimes(0);
} else {
throw new Error(
"Invalid response data - expected booking but received array of possibly recurring bookings"
@@ -0,0 +1,28 @@
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
import { BookingAttendee } from "@calcom/platform-types";
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsEnum, IsNumber, ValidateNested } from "class-validator";
export class BookingAttendeeOutput_2024_08_13 extends BookingAttendee {
@ApiProperty({ type: Number, example: 251 })
@IsNumber()
@Expose()
id!: number;
@ApiProperty({ type: Number, example: 313 })
@IsNumber()
@Expose()
bookingId!: number;
}
export class AddAttendeeOutput_2024_08_13 {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({ type: BookingAttendeeOutput_2024_08_13 })
@ValidateNested()
@Type(() => BookingAttendeeOutput_2024_08_13)
data!: BookingAttendeeOutput_2024_08_13;
}
@@ -0,0 +1,76 @@
import { BookingAttendeesService } from "@calcom/platform-libraries/bookings";
import type { AddAttendeeInput_2024_08_13 } from "@calcom/platform-types";
import { HttpException, Injectable, NotFoundException } from "@nestjs/common";
import { plainToClass } from "class-transformer";
import { BookingAttendeeOutput_2024_08_13 } from "@/ee/bookings/2024-08-13/outputs/add-attendee.output";
import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/repositories/bookings.repository";
import { PlatformBookingsService } from "@/ee/bookings/shared/platform-bookings.service";
import type { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
@Injectable()
export class BookingAttendeesService_2024_08_13 {
private bookingAttendeesService: BookingAttendeesService;
constructor(
private readonly bookingsRepository: BookingsRepository_2024_08_13,
private readonly platformBookingsService: PlatformBookingsService
) {
this.bookingAttendeesService = new BookingAttendeesService();
}
async addAttendee(
bookingUid: string,
input: AddAttendeeInput_2024_08_13,
user: ApiAuthGuardUser
): Promise<BookingAttendeeOutput_2024_08_13> {
const booking = await this.bookingsRepository.getByUidWithEventType(bookingUid);
if (!booking) {
throw new NotFoundException(`Booking with uid ${bookingUid} not found`);
}
const platformClientParams = booking.eventTypeId
? await this.platformBookingsService.getOAuthClientParams(booking.eventTypeId)
: undefined;
const emailsEnabled = platformClientParams ? platformClientParams.arePlatformEmailsEnabled : true;
const createdAttendee = await this.bookingAttendeesService.addAttendee({
bookingId: booking.id,
attendee: {
email: input.email,
name: input.name,
timeZone: input.timeZone,
phoneNumber: input.phoneNumber,
language: input.language,
},
user: {
id: user.id,
email: user.email,
organizationId: user.organizationId,
uuid: user.uuid,
},
emailsEnabled,
actionSource: "API_V2",
});
return plainToClass(
BookingAttendeeOutput_2024_08_13,
{
id: createdAttendee.id,
bookingId: createdAttendee.bookingId,
name: createdAttendee.name,
email: createdAttendee.email,
displayEmail: this.getDisplayEmail(createdAttendee.email),
timeZone: createdAttendee.timeZone,
language: createdAttendee.locale ?? undefined,
absent: false,
phoneNumber: createdAttendee.phoneNumber ?? undefined,
},
{ strategy: "excludeAll" }
);
}
private getDisplayEmail(email: string): string {
return email.replace(/\+[a-zA-Z0-9]{25}/, "");
}
}
@@ -10,6 +10,7 @@ import { BookingsRepository_2024_08_13 } from "@/ee/bookings/2024-08-13/reposito
import { BookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/bookings.service";
import { InputBookingsService_2024_08_13 } from "@/ee/bookings/2024-08-13/services/input.service";
import { EventTypesRepository_2024_06_14 } from "@/ee/event-types/event-types_2024_06_14/event-types.repository";
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
import { ApiAuthGuardUser } from "@/modules/auth/strategies/api-auth/api-auth.strategy";
import { EventTypeAccessService } from "@/modules/event-types/services/event-type-access.service";
@@ -26,7 +27,8 @@ export class BookingLocationService_2024_08_13 {
private readonly inputService: InputBookingsService_2024_08_13,
private readonly eventTypesRepository: EventTypesRepository_2024_06_14,
private readonly eventTypeAccessService: EventTypeAccessService,
private readonly bookingEventHandlerService: BookingEventHandlerService
private readonly bookingEventHandlerService: BookingEventHandlerService,
private readonly featuresRepository: PrismaFeaturesRepository
) {}
async updateBookingLocation(
@@ -99,10 +101,15 @@ export class BookingLocationService_2024_08_13 {
responses: updatedBookingResponses,
});
const organizationId = existingBookingHost.organizationId ?? null;
const isBookingAuditEnabled = organizationId
? await this.featuresRepository.checkIfTeamHasFeature(organizationId, "booking-audit")
: false;
await this.bookingEventHandlerService.onLocationChanged({
bookingUid: existingBooking.uid,
actor: makeUserActor(user.uuid),
organizationId: existingBookingHost.organizationId ?? null,
organizationId,
source: "API_V2",
auditData: {
location: {
@@ -110,6 +117,7 @@ export class BookingLocationService_2024_08_13 {
new: bookingLocation,
},
},
isBookingAuditEnabled,
});
return this.bookingsService.getBooking(updatedBooking.uid, user);
@@ -1005,7 +1005,7 @@ export class BookingsService_2024_08_13 {
bookingUid: string,
bookingOwnerId: number,
body: MarkAbsentBookingInput_2024_08_13,
userUuid?: string
userUuid: string
) {
const bodyTransformed = this.inputService.transformInputMarkAbsentBooking(body);
const bookingBefore = await this.bookingsRepository.getByUid(bookingUid);
@@ -1034,6 +1034,8 @@ export class BookingsService_2024_08_13 {
userId: bookingOwnerId,
userUuid,
platformClientParams,
actor: makeUserActor(userUuid),
actionSource: "API_V2",
});
const booking = await this.bookingsRepository.getByUidWithAttendeesAndUserAndEvent(bookingUid);
@@ -190,7 +190,10 @@ export class InputBookingsService_2024_08_13 {
eventTypeId: inputBooking.eventTypeId,
timeZone: inputBooking.attendee.timeZone,
language: inputBooking.attendee.language || "en",
metadata: inputBooking.metadata || {},
metadata: {
...(inputBooking.metadata || {}),
...(platformClientId && { platformClientId }),
},
hasHashedBookingLink: false,
guests,
verificationCode: inputBooking.emailVerificationCode,
@@ -7,8 +7,10 @@ import { Scope } from "@nestjs/common";
import { BookingAuditProducerService } from "@/lib/services/booking-audit-producer.service";
import { HashedLinkService } from "@/lib/services/hashed-link.service";
import { TaskerService } from "@/lib/services/tasker.service";
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
import { PrismaWorkerModule } from "@/modules/prisma/prisma-worker.module";
@Module({
imports: [RegularBookingModule],
imports: [RegularBookingModule, PrismaWorkerModule],
providers: [
RecurringBookingService,
BookingEventHandlerService,
@@ -24,6 +26,8 @@ import { TaskerService } from "@/lib/services/tasker.service";
BookingAuditProducerService,
TaskerService,
/** Required by BookingEventHandlerService - Ends **/
/** Required by RecurringBookingService **/
PrismaFeaturesRepository,
],
exports: [RecurringBookingService],
})
@@ -21,6 +21,10 @@ import { TaskerService } from "@/lib/services/tasker.service";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { Module, Scope } from "@nestjs/common";
import { getWebhookProducer } from "@calcom/platform-libraries/bookings";
import { WEBHOOK_PRODUCER } from "./regular-booking.tokens";
@Module({
imports: [PrismaModule],
providers: [
@@ -37,6 +41,10 @@ import { Module, Scope } from "@nestjs/common";
},
scope: Scope.TRANSIENT,
},
{
provide: WEBHOOK_PRODUCER,
useFactory: () => getWebhookProducer(),
},
BookingAuditProducerService,
BookingEventHandlerService,
CheckBookingAndDurationLimitsService,
@@ -51,6 +59,6 @@ import { Module, Scope } from "@nestjs/common";
TaskerService,
RegularBookingService,
],
exports: [RegularBookingService],
exports: [RegularBookingService, WEBHOOK_PRODUCER],
})
export class RegularBookingModule {}
@@ -0,0 +1,8 @@
/**
* Injection token for IWebhookProducerService.
* Used to bridge the Cal.com DI container into NestJS.
*
* Defined in a separate file to avoid a circular import between
* regular-booking.module.ts and regular-booking.service.ts.
*/
export const WEBHOOK_PRODUCER = "WEBHOOK_PRODUCER";
+36 -3
View File
@@ -1,9 +1,14 @@
import type { OAuth2Tokens } from "@calcom/platform-libraries";
import { OAuthService as BaseOAuthService } from "@calcom/platform-libraries";
import { Injectable } from "@nestjs/common";
import { PrismaAccessCodeRepository } from "@/lib/repositories/prisma-access-code.repository";
import { PrismaOAuthClientRepository } from "@/lib/repositories/prisma-oauth-client.repository";
import { PrismaTeamRepository } from "@/lib/repositories/prisma-team.repository";
import { Injectable } from "@nestjs/common";
import { OAuthService as BaseOAuthService } from "@calcom/platform-libraries";
import type { OAuth2ExchangeInput } from "@/modules/auth/oauth2/inputs/exchange.input";
import { OAuth2ExchangeConfidentialInput } from "@/modules/auth/oauth2/inputs/exchange.input";
import type { OAuth2RefreshInput } from "@/modules/auth/oauth2/inputs/refresh.input";
import { OAuth2RefreshConfidentialInput } from "@/modules/auth/oauth2/inputs/refresh.input";
import type { OAuth2TokenInput } from "@/modules/auth/oauth2/inputs/token.input.pipe";
@Injectable()
export class OAuthService extends BaseOAuthService {
@@ -18,4 +23,32 @@ export class OAuthService extends BaseOAuthService {
teamsRepository: teamsRepository,
});
}
async handleTokenRequest(clientId: string, body: OAuth2TokenInput): Promise<OAuth2Tokens> {
switch (body.grant_type) {
case "authorization_code":
return this.exchangeAuthorizationCode(clientId, body);
case "refresh_token":
return this.refreshToken(clientId, body);
}
}
private async exchangeAuthorizationCode(
clientId: string,
body: OAuth2ExchangeInput
): Promise<OAuth2Tokens> {
if (body instanceof OAuth2ExchangeConfidentialInput) {
return this.exchangeCodeForTokens(clientId, body.code, body.client_secret, body.redirect_uri);
}
return this.exchangeCodeForTokens(clientId, body.code, undefined, body.redirect_uri, body.code_verifier);
}
private async refreshToken(clientId: string, body: OAuth2RefreshInput): Promise<OAuth2Tokens> {
if (body instanceof OAuth2RefreshConfidentialInput) {
return this.refreshAccessToken(clientId, body.refresh_token, body.client_secret);
}
return this.refreshAccessToken(clientId, body.refresh_token);
}
}
@@ -1,5 +1,6 @@
import { RegularBookingService } from "@/lib/services/regular-booking.service";
import { BookingEventHandlerService } from "@/lib/services/booking-event-handler.service";
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
import { Injectable } from "@nestjs/common";
import { RecurringBookingService as BaseRecurringBookingService } from "@calcom/platform-libraries/bookings";
@@ -8,11 +9,13 @@ import { RecurringBookingService as BaseRecurringBookingService } from "@calcom/
export class RecurringBookingService extends BaseRecurringBookingService {
constructor(
regularBookingService: RegularBookingService,
bookingEventHandler: BookingEventHandlerService
bookingEventHandler: BookingEventHandlerService,
featuresRepository: PrismaFeaturesRepository
) {
super({
regularBookingService,
bookingEventHandler,
featuresRepository,
});
}
}
@@ -1,3 +1,10 @@
import {
RegularBookingService as BaseRegularBookingService,
type IWebhookProducerService,
} from "@calcom/platform-libraries/bookings";
import type { PrismaClient } from "@calcom/prisma";
import { Inject, Injectable } from "@nestjs/common";
import { WEBHOOK_PRODUCER } from "@/lib/modules/regular-booking.tokens";
import { PrismaBookingRepository } from "@/lib/repositories/prisma-booking.repository";
import { PrismaFeaturesRepository } from "@/lib/repositories/prisma-features.repository";
import { PrismaUserRepository } from "@/lib/repositories/prisma-user.repository";
@@ -7,10 +14,6 @@ import { HashedLinkService } from "@/lib/services/hashed-link.service";
import { LuckyUserService } from "@/lib/services/lucky-user.service";
import { BookingEmailAndSmsTasker } from "@/lib/services/tasker/booking-emails-sms-tasker.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { Injectable } from "@nestjs/common";
import { RegularBookingService as BaseRegularBookingService } from "@calcom/platform-libraries/bookings";
import type { PrismaClient } from "@calcom/prisma";
@Injectable()
export class RegularBookingService extends BaseRegularBookingService {
@@ -23,7 +26,8 @@ export class RegularBookingService extends BaseRegularBookingService {
userRepository: PrismaUserRepository,
bookingEmailAndSmsTasker: BookingEmailAndSmsTasker,
featuresRepository: PrismaFeaturesRepository,
bookingEventHandler: BookingEventHandlerService
bookingEventHandler: BookingEventHandlerService,
@Inject(WEBHOOK_PRODUCER) webhookProducer: IWebhookProducerService
) {
super({
checkBookingAndDurationLimitsService,
@@ -35,6 +39,7 @@ export class RegularBookingService extends BaseRegularBookingService {
bookingEmailAndSmsTasker,
featuresRepository,
bookingEventHandler,
webhookProducer,
});
}
}
@@ -1,7 +1,6 @@
import { getTasker, type Tasker } from "@calcom/platform-libraries/tasker";
import { Injectable } from "@nestjs/common";
import { getTasker, type Tasker } from "@calcom/platform-libraries";
@Injectable()
export class TaskerService {
private readonly tasker: Tasker;
@@ -14,5 +13,3 @@ export class TaskerService {
return this.tasker;
}
}
@@ -0,0 +1,10 @@
import { Injectable, NestMiddleware } from "@nestjs/common";
import { urlencoded } from "body-parser";
import type { Request, Response } from "express";
@Injectable()
export class UrlencodedBodyMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => any): void {
urlencoded({ extended: true })(req, res, next);
}
}
@@ -1,3 +1,20 @@
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { UpdateEventTypeReturn } from "@calcom/platform-libraries/event-types";
import { listWithTeamHandler, PublicEventType } from "@calcom/platform-libraries/event-types";
import { ApiResponse } from "@calcom/platform-types";
import {
Body,
Controller,
Get,
Param,
ParseIntPipe,
Patch,
Query,
UseGuards,
VERSION_NEUTRAL,
Version,
} from "@nestjs/common";
import { ApiExcludeController as DocsExcludeController, ApiTags as DocsTags } from "@nestjs/swagger";
import { GetEventTypePublicOutput } from "@/ee/event-types/event-types_2024_04_15/outputs/get-event-type-public.output";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import {
@@ -16,24 +33,6 @@ import { IsOrgGuard } from "@/modules/auth/guards/organizations/is-org.guard";
import { RolesGuard } from "@/modules/auth/guards/roles/roles.guard";
import { IsTeamInOrg } from "@/modules/auth/guards/teams/is-team-in-org.guard";
import { UserWithProfile } from "@/modules/users/users.repository";
import {
Controller,
Get,
Param,
ParseIntPipe,
UseGuards,
Version,
VERSION_NEUTRAL,
Patch,
Body,
Query,
} from "@nestjs/common";
import { ApiTags as DocsTags, ApiExcludeController as DocsExcludeController } from "@nestjs/swagger";
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
import type { UpdateEventTypeReturn } from "@calcom/platform-libraries/event-types";
import { PublicEventType } from "@calcom/platform-libraries/event-types";
import { ApiResponse } from "@calcom/platform-types";
/*
Event-types endpoints for atoms, split from AtomsController for clarity and maintainability.
@@ -49,6 +48,17 @@ These endpoints should not be recommended for use by third party and are exclude
export class AtomsEventTypesController {
constructor(private readonly eventTypesService: EventTypesAtomService) {}
@Get("/event-types/list-with-team")
@Version(VERSION_NEUTRAL)
@UseGuards(ApiAuthGuard)
async listEventTypesWithTeam(@GetUser() user: UserWithProfile): Promise<ApiResponse<unknown>> {
const eventTypes = await listWithTeamHandler({ ctx: { user } });
return {
status: SUCCESS_STATUS,
data: eventTypes,
};
}
@Get("/event-types/:eventSlug/public")
async getPublicEventType(
@Param("eventSlug") eventSlug: string,
@@ -73,6 +73,21 @@ export class AtomsSchedulesController {
};
}
@Get("/schedules/event-type/:eventSlug")
@Version(VERSION_NEUTRAL)
@UseGuards(ApiAuthGuard)
@Permissions([SCHEDULE_READ])
async getScheduleByEventSlug(
@GetUser() user: UserWithProfile,
@Param("eventSlug") eventSlug: string
): Promise<ApiResponse<unknown>> {
const schedule = await this.schedulesService.getScheduleByEventSlug(user, eventSlug);
return {
status: SUCCESS_STATUS,
data: schedule,
};
}
@Get("/schedules/all")
@Version(VERSION_NEUTRAL)
@UseGuards(ApiAuthGuard)
@@ -1,3 +1,4 @@
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { UsersRepository } from "@/modules/users/users.repository";
import { UserWithProfile } from "@/modules/users/users.repository";
@@ -5,6 +6,7 @@ import { Logger } from "@nestjs/common";
import { Injectable } from "@nestjs/common";
import { ScheduleRepository, UpdateScheduleResponse } from "@calcom/platform-libraries/schedules";
import { getScheduleByEventSlugHandler } from "@calcom/platform-libraries/schedules";
import { updateSchedule } from "@calcom/platform-libraries/schedules";
import { UpdateAtomScheduleDto } from "@calcom/platform-types";
import type { PrismaClient } from "@calcom/prisma";
@@ -15,6 +17,7 @@ export class SchedulesAtomsService {
constructor(
private readonly usersRepository: UsersRepository,
private readonly dbRead: PrismaReadService,
private readonly dbWrite: PrismaWriteService
) {}
@@ -42,6 +45,13 @@ export class SchedulesAtomsService {
});
}
async getScheduleByEventSlug(user: UserWithProfile, eventSlug: string) {
return getScheduleByEventSlugHandler({
ctx: { user, prisma: this.dbRead.prisma as unknown as PrismaClient },
input: { eventSlug },
});
}
async updateUserSchedule({
input,
user,
@@ -1,11 +1,12 @@
import { generateSecret } from "@calcom/platform-libraries";
import type { Membership, Team, User } from "@calcom/prisma/client";
import { AccessScope, OAuthClientType } from "@calcom/prisma/enums";
import { INestApplication } from "@nestjs/common";
import { NestExpressApplication } from "@nestjs/platform-express";
import { Test, TestingModule } from "@nestjs/testing";
import { getToken } from "next-auth/jwt";
import { AccessScope, OAuthClientStatus, OAuthClientType } from "@calcom/prisma/enums";
import type { INestApplication } from "@nestjs/common";
import type { NestExpressApplication } from "@nestjs/platform-express";
import type { TestingModule } from "@nestjs/testing";
import { Test } from "@nestjs/testing";
import request from "supertest";
import { ApiKeysRepositoryFixture } from "test/fixtures/repository/api-keys.repository.fixture";
import { MembershipRepositoryFixture } from "test/fixtures/repository/membership.repository.fixture";
import { OAuth2ClientRepositoryFixture } from "test/fixtures/repository/oauth2-client.repository.fixture";
import { TeamRepositoryFixture } from "test/fixtures/repository/team.repository.fixture";
@@ -16,24 +17,21 @@ import { bootstrap } from "@/bootstrap";
import { HttpExceptionFilter } from "@/filters/http-exception.filter";
import { PrismaExceptionFilter } from "@/filters/prisma-exception.filter";
import { ZodExceptionFilter } from "@/filters/zod-exception.filter";
import { OAuthService } from "@/lib/services/oauth.service";
import { AuthModule } from "@/modules/auth/auth.module";
import { PrismaModule } from "@/modules/prisma/prisma.module";
import { UsersModule } from "@/modules/users/users.module";
// Mock next-auth/jwt getToken for ApiAuthStrategy NEXT_AUTH authentication
// Mock next-auth/jwt getToken so the NextAuth fallback in ApiAuthStrategy doesn't crash in tests
jest.mock("next-auth/jwt", () => ({
getToken: jest.fn(),
getToken: jest.fn().mockResolvedValue(null),
}));
const mockGetToken = getToken as jest.MockedFunction<typeof getToken>;
describe("OAuth2 Controller Endpoints", () => {
describe("User Not Authenticated", () => {
let appWithoutAuth: INestApplication;
beforeAll(async () => {
// Mock getToken to return null for unauthenticated tests
mockGetToken.mockResolvedValue(null);
const moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter, ZodExceptionFilter],
imports: [AppModule, UsersModule, AuthModule, PrismaModule],
@@ -49,12 +47,16 @@ describe("OAuth2 Controller Endpoints", () => {
.expect(401);
});
it("POST /v2/auth/oauth2/clients/:clientId/authorize should return 401 without auth", () => {
it("POST /v2/auth/oauth2/token should return 401 without auth", () => {
return request(appWithoutAuth.getHttpServer())
.post("/api/v2/auth/oauth2/clients/test-client-id/authorize")
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
redirectUri: "https://example.com/callback",
scopes: ["READ_BOOKING"],
client_id: "test-client-id",
grant_type: "authorization_code",
code: "test-code",
client_secret: "test-secret",
redirect_uri: "https://example.com/callback",
})
.expect(401);
});
@@ -64,33 +66,47 @@ describe("OAuth2 Controller Endpoints", () => {
});
});
describe("User Authenticated", () => {
describe("User Authenticated (non-owner)", () => {
let app: INestApplication;
let moduleRef: TestingModule;
let userRepositoryFixture: UserRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let membershipRepositoryFixture: MembershipRepositoryFixture;
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
let oAuthClientFixture: OAuth2ClientRepositoryFixture;
let oAuthService: OAuthService;
let user: User;
let clientOwner: User;
let authenticatedUser: User;
let team: Team;
let membership: Membership;
let oAuthClient: { clientId: string };
let authorizationCode: string;
let apiKeyString: string;
let refreshToken: string;
const testClientId = `test-oauth-client-${randomString()}`;
const testClientSecret = "test-secret-123";
const testRedirectUri = "https://example.com/callback";
/** Generate an authorization code directly via the service (bypasses HTTP layer). */
async function generateAuthCode(
scopes: AccessScope[] = [AccessScope.READ_BOOKING],
teamSlug?: string
): Promise<string> {
const result = await oAuthService.generateAuthorizationCode(
testClientId,
authenticatedUser.id,
testRedirectUri,
scopes,
undefined,
teamSlug ?? team.slug
);
const redirectUrl = new URL(result.redirectUrl);
return redirectUrl.searchParams.get("code") as string;
}
beforeAll(async () => {
const userEmail = `oauth2-e2e-user-${randomString()}@api.com`;
// Mock getToken to return the user email for authenticated tests
// This is needed because ApiAuthGuard uses ApiAuthStrategy which calls getToken from next-auth/jwt
mockGetToken.mockResolvedValue({ email: userEmail });
moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter, ZodExceptionFilter],
imports: [AppModule, UsersModule, AuthModule, PrismaModule],
@@ -103,19 +119,28 @@ describe("OAuth2 Controller Endpoints", () => {
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
membershipRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef);
oAuthClientFixture = new OAuth2ClientRepositoryFixture(moduleRef);
oAuthService = moduleRef.get(OAuthService);
user = await userRepositoryFixture.create({
email: userEmail,
clientOwner = await userRepositoryFixture.create({
email: `oauth2-e2e-owner-${randomString()}@api.com`,
});
authenticatedUser = await userRepositoryFixture.create({
email: `oauth2-e2e-user-${randomString()}@api.com`,
});
const { keyString } = await apiKeysRepositoryFixture.createApiKey(authenticatedUser.id, null);
apiKeyString = keyString;
team = await teamRepositoryFixture.create({
name: `oauth2-e2e-team-${randomString()}`,
slug: `oauth2-e2e-team-${randomString()}`,
});
membership = await membershipRepositoryFixture.create({
user: { connect: { id: user.id } },
user: { connect: { id: authenticatedUser.id } },
team: { connect: { id: team.id } },
role: "OWNER",
accepted: true,
@@ -128,180 +153,285 @@ describe("OAuth2 Controller Endpoints", () => {
redirectUri: testRedirectUri,
clientSecret: hashedSecret,
clientType: OAuthClientType.CONFIDENTIAL,
userId: clientOwner.id,
});
});
describe("GET /api/v2/auth/oauth2/clients/:clientId", () => {
it("should return OAuth client info for valid client ID", async () => {
const response = await request(app.getHttpServer())
.get(`/api/v2/auth/oauth2/clients/${testClientId}`)
.expect(200);
describe("Positive tests", () => {
it("should return OAuth client info for valid client ID", async () => {
const response = await request(app.getHttpServer())
.get(`/api/v2/auth/oauth2/clients/${testClientId}`)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.expect(200);
expect(response.body.status).toBe("success");
expect(response.body.data.id).toBe(testClientId);
expect(response.body.data.name).toBe("Test OAuth Client");
expect(response.body.data.redirectUri).toBe(testRedirectUri);
expect(response.body.data.type).toBe(OAuthClientType.CONFIDENTIAL);
expect(response.body.data.clientSecret).toBeUndefined();
expect(response.body.status).toBe("success");
expect(response.body.data.client_id).toBe(testClientId);
expect(response.body.data.name).toBe("Test OAuth Client");
expect(response.body.data.redirect_uri).toBe(testRedirectUri);
expect(response.body.data.client_type).toBe(OAuthClientType.CONFIDENTIAL);
expect(response.body.data.client_secret).toBeUndefined();
});
});
it("should return 404 for non-existent client ID", async () => {
await request(app.getHttpServer())
.get("/api/v2/auth/oauth2/clients/non-existent-client-id")
.expect(404);
describe("Negative tests", () => {
it("should return 404 for non-existent client ID", async () => {
await request(app.getHttpServer())
.get("/api/v2/auth/oauth2/clients/non-existent-client-id")
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.expect(404);
});
});
});
describe("POST /api/v2/auth/oauth2/clients/:clientId/authorize", () => {
it("should redirect with authorization code for valid request", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING, AccessScope.READ_PROFILE],
teamSlug: team.slug,
state: "test-state-123",
})
.expect(303);
describe("POST /api/v2/auth/oauth2/token (authorization_code grant)", () => {
describe("Positive tests", () => {
it("should exchange authorization code for tokens", async () => {
const authorizationCode = await generateAuthCode([
AccessScope.READ_BOOKING,
AccessScope.READ_PROFILE,
]);
expect(response.headers.location).toBeDefined();
const redirectUrl = new URL(response.headers.location);
expect(redirectUrl.origin + redirectUrl.pathname).toBe(testRedirectUri);
expect(redirectUrl.searchParams.get("code")).toBeDefined();
expect(redirectUrl.searchParams.get("state")).toBe("test-state-123");
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "authorization_code",
code: authorizationCode,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
authorizationCode = redirectUrl.searchParams.get("code") as string;
expect(response.body.access_token).toBeDefined();
expect(response.body.refresh_token).toBeDefined();
expect(response.body.token_type).toBe("bearer");
expect(response.body.expires_in).toBe(1800);
expect(response.headers["cache-control"]).toBe("no-store");
expect(response.headers["pragma"]).toBe("no-cache");
refreshToken = response.body.refresh_token;
});
it("should exchange authorization code for tokens with JSON body", async () => {
const code = await generateAuthCode();
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.send({
client_id: testClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
expect(response.body.access_token).toBeDefined();
expect(response.body.refresh_token).toBeDefined();
expect(response.body.token_type).toBe("bearer");
});
it("should exchange authorization code for tokens with application/x-www-form-urlencoded body", async () => {
const code = await generateAuthCode();
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
expect(response.body.access_token).toBeDefined();
expect(response.body.refresh_token).toBeDefined();
expect(response.body.token_type).toBe("bearer");
expect(response.body.expires_in).toBe(1800);
});
});
it("should redirect with error for invalid client ID", async () => {
await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/clients/invalid-client-id/authorize")
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING],
})
.expect(404);
});
describe("Negative tests", () => {
it("should return 400 with RFC 6749 error for invalid/used authorization code", async () => {
const code = await generateAuthCode();
it("should redirect with error for invalid team slug", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING],
teamSlug: "non-existent-team-slug",
state: "test-state-456",
})
.expect(303);
// Use the code once
await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
expect(response.headers.location).toBeDefined();
const redirectUrl = new URL(response.headers.location);
expect(redirectUrl.searchParams.get("error")).toBe("access_denied");
expect(redirectUrl.searchParams.get("state")).toBe("test-state-456");
});
// Try to use the same code again
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(400);
it("should throw error 400 for mismatched redirect URI", async () => {
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: "https://wrong-domain.com/callback",
scopes: [AccessScope.READ_BOOKING],
state: "test-state-789",
})
.expect(400);
expect(response.body.error).toBe("invalid_grant");
expect(response.body.error_description).toBe("code_invalid_or_expired");
});
it("should return 401 for invalid client secret", async () => {
const code = await generateAuthCode();
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "authorization_code",
code,
client_secret: "wrong-secret",
redirect_uri: testRedirectUri,
})
.expect(401);
expect(response.body.error).toBe("invalid_client");
expect(response.body.error_description).toBe("invalid_client_credentials");
});
it("should return 400 for invalid grant type", async () => {
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "invalid_grant",
code: "some-code",
redirect_uri: testRedirectUri,
})
.expect(400);
expect(response.body.error).toBe("invalid_request");
expect(response.body.error_description).toBe(
"grant_type must be 'authorization_code' or 'refresh_token'"
);
});
it("should return 401 with RFC 6749 error for non-existent client_id", async () => {
const code = await generateAuthCode();
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: "non-existent-client-id",
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(401);
expect(response.body.error).toBe("invalid_client");
expect(response.body.error_description).toBe("client_not_found");
});
it("should return 400 with RFC 6749 error when client_id is missing", async () => {
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
grant_type: "authorization_code",
code: "some-code",
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(400);
expect(response.body.error).toBe("invalid_request");
expect(response.body.error_description).toBe("client_id is required");
});
});
});
describe("POST /api/v2/auth/oauth2/clients/:clientId/exchange", () => {
it("should exchange authorization code for tokens", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/exchange`)
.send({
code: authorizationCode,
clientSecret: testClientSecret,
redirectUri: testRedirectUri,
})
.expect(200);
describe("POST /api/v2/auth/oauth2/token (refresh_token grant)", () => {
describe("Positive tests", () => {
it("should refresh access token with valid refresh token", async () => {
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "refresh_token",
refresh_token: refreshToken,
client_secret: testClientSecret,
})
.expect(200);
expect(response.body.status).toBe("success");
expect(response.body.data.access_token).toBeDefined();
expect(response.body.data.refresh_token).toBeDefined();
expect(response.body.data.token_type).toBe("bearer");
expect(response.body.data.expires_in).toBe(1800);
refreshToken = response.body.data.refresh_token;
expect(response.body.access_token).toBeDefined();
expect(response.body.refresh_token).toBeDefined();
expect(response.body.token_type).toBe("bearer");
expect(response.body.expires_in).toBe(1800);
});
});
it("should return 400 for invalid/used authorization code", async () => {
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/exchange`)
.send({
code: authorizationCode,
clientSecret: testClientSecret,
redirectUri: testRedirectUri,
})
.expect(400);
});
describe("Negative tests", () => {
it("should return 400 with RFC 6749 error for invalid refresh token", async () => {
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "refresh_token",
refresh_token: "invalid-refresh-token",
client_secret: testClientSecret,
})
.expect(400);
it("should return 401 for invalid client secret", async () => {
const newAuthResponse = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/authorize`)
.send({
redirectUri: testRedirectUri,
scopes: [AccessScope.READ_BOOKING],
teamSlug: team.slug,
})
.expect(303);
expect(response.body.error).toBe("invalid_grant");
expect(response.body.error_description).toBe("invalid_refresh_token");
});
const newRedirectUrl = new URL(newAuthResponse.headers.location);
const newAuthCode = newRedirectUrl.searchParams.get("code") as string;
it("should return 401 for invalid client secret", async () => {
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: testClientId,
grant_type: "refresh_token",
refresh_token: refreshToken,
client_secret: "wrong-secret",
})
.expect(401);
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/exchange`)
.send({
code: newAuthCode,
clientSecret: "wrong-secret",
redirectUri: testRedirectUri,
})
.expect(401);
});
});
expect(response.body.error).toBe("invalid_client");
expect(response.body.error_description).toBe("invalid_client_credentials");
});
describe("POST /api/v2/auth/oauth2/clients/:clientId/refresh", () => {
it("should refresh access token with valid refresh token", async () => {
const response = await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/refresh`)
.send({
refreshToken: refreshToken,
clientSecret: testClientSecret,
})
.expect(200);
it("should return 401 with RFC 6749 error for non-existent client_id", async () => {
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: "wrong-client-id",
grant_type: "refresh_token",
refresh_token: refreshToken,
client_secret: testClientSecret,
})
.expect(401);
expect(response.body.status).toBe("success");
expect(response.body.data.access_token).toBeDefined();
expect(response.body.data.refresh_token).toBeDefined();
expect(response.body.data.token_type).toBe("bearer");
expect(response.body.data.expires_in).toBe(1800);
});
it("should return 400 for invalid refresh token", async () => {
await request(app.getHttpServer())
.post(`/api/v2/auth/oauth2/clients/${testClientId}/refresh`)
.send({
refreshToken: "invalid-refresh-token",
clientSecret: testClientSecret,
})
.expect(400);
});
it("should return 401 for wrong client ID with valid refresh token", async () => {
await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/clients/wrong-client-id/refresh")
.send({
refreshToken: refreshToken,
clientSecret: testClientSecret,
})
.expect(401);
expect(response.body.error).toBe("invalid_client");
expect(response.body.error_description).toBe("client_not_found");
});
});
});
@@ -309,7 +439,238 @@ describe("OAuth2 Controller Endpoints", () => {
await oAuthClientFixture.delete(oAuthClient.clientId);
await membershipRepositoryFixture.delete(membership.id);
await teamRepositoryFixture.delete(team.id);
await userRepositoryFixture.delete(user.id);
await userRepositoryFixture.delete(authenticatedUser.id);
await userRepositoryFixture.delete(clientOwner.id);
await app.close();
});
});
describe("Owner can use non-approved OAuth client", () => {
let app: INestApplication;
let moduleRef: TestingModule;
let userRepositoryFixture: UserRepositoryFixture;
let teamRepositoryFixture: TeamRepositoryFixture;
let membershipRepositoryFixture: MembershipRepositoryFixture;
let apiKeysRepositoryFixture: ApiKeysRepositoryFixture;
let oAuthClientFixture: OAuth2ClientRepositoryFixture;
let oAuthService: OAuthService;
let owner: User;
let team: Team;
let membership: Membership;
let pendingClient: { clientId: string };
let rejectedClient: { clientId: string };
let apiKeyString: string;
const pendingClientId = `test-pending-client-${randomString()}`;
const rejectedClientId = `test-rejected-client-${randomString()}`;
const testClientSecret = "test-secret-456";
const testRedirectUri = "https://example.com/callback";
/** Generate a user-scoped authorization code (no teamSlug) so the owner's userId is in the token. */
async function generateAuthCodeForClient(
clientId: string,
scopes: AccessScope[] = [AccessScope.READ_BOOKING]
): Promise<string> {
const result = await oAuthService.generateAuthorizationCode(
clientId,
owner.id,
testRedirectUri,
scopes
);
const redirectUrl = new URL(result.redirectUrl);
return redirectUrl.searchParams.get("code") as string;
}
beforeAll(async () => {
moduleRef = await Test.createTestingModule({
providers: [PrismaExceptionFilter, HttpExceptionFilter, ZodExceptionFilter],
imports: [AppModule, UsersModule, AuthModule, PrismaModule],
}).compile();
app = moduleRef.createNestApplication();
bootstrap(app as NestExpressApplication);
await app.init();
userRepositoryFixture = new UserRepositoryFixture(moduleRef);
teamRepositoryFixture = new TeamRepositoryFixture(moduleRef);
membershipRepositoryFixture = new MembershipRepositoryFixture(moduleRef);
apiKeysRepositoryFixture = new ApiKeysRepositoryFixture(moduleRef);
oAuthClientFixture = new OAuth2ClientRepositoryFixture(moduleRef);
oAuthService = moduleRef.get(OAuthService);
owner = await userRepositoryFixture.create({
email: `oauth2-owner-e2e-${randomString()}@api.com`,
});
const { keyString } = await apiKeysRepositoryFixture.createApiKey(owner.id, null);
apiKeyString = keyString;
team = await teamRepositoryFixture.create({
name: `oauth2-owner-team-${randomString()}`,
slug: `oauth2-owner-team-${randomString()}`,
});
membership = await membershipRepositoryFixture.create({
user: { connect: { id: owner.id } },
team: { connect: { id: team.id } },
role: "OWNER",
accepted: true,
});
const [hashedSecret] = generateSecret(testClientSecret);
pendingClient = await oAuthClientFixture.create({
clientId: pendingClientId,
name: "Pending OAuth Client",
redirectUri: testRedirectUri,
clientSecret: hashedSecret,
clientType: OAuthClientType.CONFIDENTIAL,
status: OAuthClientStatus.PENDING,
userId: owner.id,
});
rejectedClient = await oAuthClientFixture.create({
clientId: rejectedClientId,
name: "Rejected OAuth Client",
redirectUri: testRedirectUri,
clientSecret: hashedSecret,
clientType: OAuthClientType.CONFIDENTIAL,
status: OAuthClientStatus.REJECTED,
userId: owner.id,
});
});
it("should return PENDING client info when authenticated as owner", async () => {
const response = await request(app.getHttpServer())
.get(`/api/v2/auth/oauth2/clients/${pendingClientId}`)
.set({ Authorization: `Bearer cal_test_${apiKeyString}` })
.expect(200);
expect(response.body.status).toBe("success");
expect(response.body.data.client_id).toBe(pendingClientId);
expect(response.body.data.name).toBe("Pending OAuth Client");
});
it("should exchange authorization code for tokens with PENDING client owned by user", async () => {
const code = await generateAuthCodeForClient(pendingClientId);
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: pendingClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
expect(response.body.access_token).toBeDefined();
expect(response.body.refresh_token).toBeDefined();
expect(response.body.token_type).toBe("bearer");
});
it("should refresh tokens with PENDING client owned by user", async () => {
const code = await generateAuthCodeForClient(pendingClientId);
const tokenResponse = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: pendingClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: pendingClientId,
grant_type: "refresh_token",
refresh_token: tokenResponse.body.refresh_token,
client_secret: testClientSecret,
})
.expect(200);
expect(response.body.access_token).toBeDefined();
expect(response.body.refresh_token).toBeDefined();
expect(response.body.token_type).toBe("bearer");
});
it("should reject authorization code generation for REJECTED client even as owner", async () => {
await expect(generateAuthCodeForClient(rejectedClientId)).rejects.toThrow();
});
it("should reject token exchange when client becomes rejected", async () => {
const code = await generateAuthCodeForClient(pendingClientId);
await oAuthClientFixture.updateStatus(pendingClientId, OAuthClientStatus.REJECTED);
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: pendingClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(401);
expect(response.body.error).toBe("unauthorized_client");
expect(response.body.error_description).toBe("client_rejected");
await oAuthClientFixture.updateStatus(pendingClientId, OAuthClientStatus.PENDING);
});
it("should reject token refresh when client becomes rejected", async () => {
const code = await generateAuthCodeForClient(pendingClientId);
const tokenResponse = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: pendingClientId,
grant_type: "authorization_code",
code,
client_secret: testClientSecret,
redirect_uri: testRedirectUri,
})
.expect(200);
await oAuthClientFixture.updateStatus(pendingClientId, OAuthClientStatus.REJECTED);
const response = await request(app.getHttpServer())
.post("/api/v2/auth/oauth2/token")
.type("form")
.send({
client_id: pendingClientId,
grant_type: "refresh_token",
refresh_token: tokenResponse.body.refresh_token,
client_secret: testClientSecret,
})
.expect(401);
expect(response.body.error).toBe("unauthorized_client");
expect(response.body.error_description).toBe("client_rejected");
await oAuthClientFixture.updateStatus(pendingClientId, OAuthClientStatus.PENDING);
});
afterAll(async () => {
await oAuthClientFixture.delete(pendingClient.clientId);
await oAuthClientFixture.delete(rejectedClient.clientId);
await membershipRepositoryFixture.delete(membership.id);
await teamRepositoryFixture.delete(team.id);
await userRepositoryFixture.delete(owner.id);
await app.close();
});
});
@@ -1,46 +1,48 @@
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { OAuthService } from "@/lib/services/oauth.service";
import { ApiAuthGuardOnlyAllow } from "@/modules/auth/decorators/api-auth-guard-only-allow.decorator";
import { GetUser } from "@/modules/auth/decorators/get-user/get-user.decorator";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { OAuth2AuthorizeInput } from "@/modules/auth/oauth2/inputs/authorize.input";
import { OAuth2ExchangeInput } from "@/modules/auth/oauth2/inputs/exchange.input";
import { OAuth2RefreshInput } from "@/modules/auth/oauth2/inputs/refresh.input";
import { OAuth2ClientDto, OAuth2ClientResponseDto } from "@/modules/auth/oauth2/outputs/oauth2-client.output";
import { OAuth2TokensDto, OAuth2TokensResponseDto } from "@/modules/auth/oauth2/outputs/oauth2-tokens.output";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import {
Body,
Controller,
Get,
Header,
HttpCode,
HttpException,
HttpStatus,
InternalServerErrorException,
Logger,
Param,
Post,
Res,
UseFilters,
UseGuards,
} from "@nestjs/common";
import { ApiExcludeController, ApiOperation, ApiTags } from "@nestjs/swagger";
import { ApiBody, ApiExtraModels, ApiOperation, ApiTags, getSchemaPath } from "@nestjs/swagger";
import { plainToInstance } from "class-transformer";
import type { Response } from "express";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
import { ErrorWithCode, getHttpStatusCode } from "@calcom/platform-libraries/errors";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { OAuthService } from "@/lib/services/oauth.service";
import { ApiAuthGuard } from "@/modules/auth/guards/api-auth/api-auth.guard";
import { OAuth2HttpExceptionFilter } from "@/modules/auth/oauth2/filters/oauth2-http-exception.filter";
import {
OAuth2ExchangeConfidentialInput,
OAuth2ExchangePublicInput,
} from "@/modules/auth/oauth2/inputs/exchange.input";
import {
OAuth2RefreshConfidentialInput,
OAuth2RefreshPublicInput,
} from "@/modules/auth/oauth2/inputs/refresh.input";
import type { OAuth2TokenInput } from "@/modules/auth/oauth2/inputs/token.input.pipe";
import { OAuth2TokenInputPipe } from "@/modules/auth/oauth2/inputs/token.input.pipe";
import { OAuth2ClientDto, OAuth2ClientResponseDto } from "@/modules/auth/oauth2/outputs/oauth2-client.output";
import { OAuth2TokensDto } from "@/modules/auth/oauth2/outputs/oauth2-tokens.output";
import { OAuth2ErrorService } from "@/modules/auth/oauth2/services/oauth2-error.service";
@Controller({
path: "/v2/auth/oauth2/clients/:clientId",
path: "/v2/auth/oauth2",
version: API_VERSIONS_VALUES,
})
@ApiExcludeController(true)
@ApiTags("OAuth2")
export class OAuth2Controller {
private readonly logger = new Logger("OAuth2Controller");
constructor(
private readonly oAuthService: OAuthService,
private readonly errorHandler: OAuth2ErrorService
) {}
constructor(private readonly oAuthService: OAuthService) {}
@Get("/")
@Get("/clients/:clientId")
@HttpCode(HttpStatus.OK)
@UseGuards(ApiAuthGuard)
@ApiOperation({
@@ -55,114 +57,50 @@ export class OAuth2Controller {
status: SUCCESS_STATUS,
data: plainToInstance(OAuth2ClientDto, client, { strategy: "excludeAll" }),
};
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException("Could not get oAuthClient");
} catch (err) {
this.errorHandler.handleClientError(err, "Failed to retrieve OAuth client");
}
}
@Post("/authorize")
@UseGuards(ApiAuthGuard)
@ApiAuthGuardOnlyAllow(["NEXT_AUTH"])
@Post("/token")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Generate authorization code",
summary: "Exchange authorization code or refresh token for tokens",
description:
"Generates an authorization code for the OAuth2 flow and redirects to the redirect URI with the code. Requires user authentication.",
"RFC 6749-compliant token endpoint. Pass client_id in the request body (Section 2.3.1). " +
"Use grant_type 'authorization_code' to exchange an auth code for tokens, or 'refresh_token' to refresh an access token. " +
"Accepts both application/x-www-form-urlencoded (standard per RFC 6749 Section 4.1.3) and application/json content types.",
})
async authorize(
@Param("clientId") clientId: string,
@Body() body: OAuth2AuthorizeInput,
@GetUser("id") userId: number,
@Res() res: Response
): Promise<void> {
@ApiBody({
schema: {
oneOf: [
{ $ref: getSchemaPath(OAuth2ExchangeConfidentialInput) },
{ $ref: getSchemaPath(OAuth2ExchangePublicInput) },
{ $ref: getSchemaPath(OAuth2RefreshConfidentialInput) },
{ $ref: getSchemaPath(OAuth2RefreshPublicInput) },
],
},
description:
"Token request body. client_id is required. " +
"Accepts application/x-www-form-urlencoded (RFC 6749 standard) or application/json. " +
"Use grant_type 'authorization_code' with client_secret (confidential) or code_verifier (public/PKCE), or grant_type 'refresh_token' with client_secret (confidential) or just the refresh_token (public).",
})
@ApiExtraModels(
OAuth2ExchangeConfidentialInput,
OAuth2ExchangePublicInput,
OAuth2RefreshConfidentialInput,
OAuth2RefreshPublicInput
)
@UseFilters(OAuth2HttpExceptionFilter)
@Header("Cache-Control", "no-store")
@Header("Pragma", "no-cache")
async token(@Body(new OAuth2TokenInputPipe()) body: OAuth2TokenInput): Promise<OAuth2TokensDto> {
try {
const client = await this.oAuthService.getClient(clientId);
const result = await this.oAuthService.generateAuthorizationCode(
client.clientId,
userId,
body.redirectUri,
body.scopes,
body.state,
body.teamSlug,
body.codeChallenge,
body.codeChallengeMethod
);
return res.redirect(303, result.redirectUrl);
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
if (err.message === "unauthorized_client" || err?.data?.["reason"] === "redirect_uri_mismatch") {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
}
const errorRedirectUrl = this.oAuthService.buildErrorRedirectUrl(body.redirectUri, err, body.state);
return res.redirect(303, errorRedirectUrl);
}
}
const tokens = await this.oAuthService.handleTokenRequest(body.client_id, body);
@Post("/exchange")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Exchange authorization code for tokens",
description: "Exchanges an authorization code for access and refresh tokens",
})
async exchange(
@Param("clientId") clientId: string,
@Body() body: OAuth2ExchangeInput
): Promise<OAuth2TokensResponseDto> {
try {
const tokens = await this.oAuthService.exchangeCodeForTokens(
clientId,
body.code,
body.clientSecret,
body.redirectUri,
body.codeVerifier
);
return {
status: SUCCESS_STATUS,
data: plainToInstance(OAuth2TokensDto, tokens, { strategy: "excludeAll" }),
};
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException("Could not exchange code for tokens");
}
}
@Post("/refresh")
@HttpCode(HttpStatus.OK)
@ApiOperation({
summary: "Refresh access token",
description: "Refreshes an access token using a refresh token",
})
async refresh(
@Param("clientId") clientId: string,
@Body() body: OAuth2RefreshInput
): Promise<OAuth2TokensResponseDto> {
try {
const tokens = await this.oAuthService.refreshAccessToken(
clientId,
body.refreshToken,
body.clientSecret
);
return {
status: SUCCESS_STATUS,
data: plainToInstance(OAuth2TokensDto, tokens, { strategy: "excludeAll" }),
};
} catch (err: unknown) {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException("Could not refresh tokens");
return plainToInstance(OAuth2TokensDto, tokens, { strategy: "excludeAll" });
} catch (err) {
this.errorHandler.handleTokenError(err);
}
}
}
@@ -0,0 +1,33 @@
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
import { Catch, Logger } from "@nestjs/common";
import type { Request, Response } from "express";
import { extractUserContext } from "@/lib/extract-user-context";
import { filterReqHeaders } from "@/lib/filterReqHeaders";
import { OAuth2HttpException } from "@/modules/auth/oauth2/filters/oauth2-http.exception";
@Catch(OAuth2HttpException)
export class OAuth2HttpExceptionFilter implements ExceptionFilter<OAuth2HttpException> {
private readonly logger = new Logger("OAuth2HttpExceptionFilter");
catch(exception: OAuth2HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const request = ctx.getRequest<Request>();
const requestId = request.headers["x-request-id"] ?? "unknown-request-id";
response.setHeader("X-Request-Id", requestId.toString());
const { userEmail: _userEmail, ...safeUserContext } = extractUserContext(request);
const { Authorization: _auth, ...safeHeaders } = filterReqHeaders(request.headers);
this.logger.error(`OAuth2 Http Exception: ${exception.oAuthErrorData.error}`, {
exception,
body: "[REDACTED]",
headers: safeHeaders,
url: request.url,
method: request.method,
requestId,
...safeUserContext,
});
response.status(exception.getStatus()).json(exception.oAuthErrorData);
}
}
@@ -0,0 +1,10 @@
import { HttpException } from "@nestjs/common";
export class OAuth2HttpException extends HttpException {
constructor(
public readonly oAuthErrorData: { error: string; error_description: string },
statusCode: number
) {
super(oAuthErrorData, statusCode);
}
}
@@ -0,0 +1,14 @@
import type { ArgumentsHost, ExceptionFilter } from "@nestjs/common";
import { Catch } from "@nestjs/common";
import type { Response } from "express";
import { OAuth2RedirectException } from "@/modules/auth/oauth2/filters/oauth2-redirect.exception";
@Catch(OAuth2RedirectException)
export class OAuth2RedirectExceptionFilter implements ExceptionFilter<OAuth2RedirectException> {
catch(exception: OAuth2RedirectException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
response.redirect(303, exception.redirectUrl);
}
}
@@ -0,0 +1,10 @@
import { HttpException, HttpStatus } from "@nestjs/common";
export class OAuth2RedirectException extends HttpException {
readonly redirectUrl: string;
constructor(redirectUrl: string) {
super("OAuth2 redirect", HttpStatus.SEE_OTHER);
this.redirectUrl = redirectUrl;
}
}
@@ -1,8 +1,7 @@
import { AccessScope } from "@calcom/prisma/enums";
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
import { Equals, IsArray, IsEnum, IsOptional, IsString } from "class-validator";
import { AccessScope } from "@calcom/prisma/enums";
export class OAuth2AuthorizeInput {
@ApiProperty({
description:
@@ -10,7 +9,7 @@ export class OAuth2AuthorizeInput {
example: "https://example.com/callback",
})
@IsString()
redirectUri!: string;
redirect_uri!: string;
@ApiProperty({
description: "OAuth state parameter for CSRF protection. Will be included in the redirect.",
@@ -36,7 +35,7 @@ export class OAuth2AuthorizeInput {
})
@IsOptional()
@IsString()
teamSlug?: string;
team_slug?: string;
@ApiProperty({
description: "PKCE code challenge (required for public clients)",
@@ -44,10 +43,10 @@ export class OAuth2AuthorizeInput {
})
@IsOptional()
@IsString()
codeChallenge?: string;
code_challenge?: string;
@ApiHideProperty()
@IsString()
@Equals("S256")
codeChallengeMethod: string = "S256";
code_challenge_method: string = "S256";
}
@@ -1,7 +1,23 @@
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
import { Equals, IsOptional, IsString } from "class-validator";
import { ApiProperty } from "@nestjs/swagger";
import { Equals, IsString } from "class-validator";
export class OAuth2ExchangeConfidentialInput {
@ApiProperty({
description: "The client identifier",
example: "my-client-id",
})
@IsString()
client_id!: string;
@ApiProperty({
description: "The grant type — must be 'authorization_code'",
example: "authorization_code",
enum: ["authorization_code"],
})
@IsString()
@Equals("authorization_code")
grant_type!: "authorization_code";
export class OAuth2ExchangeInput {
@ApiProperty({
description: "The authorization code received from the authorize endpoint",
example: "abc123",
@@ -10,30 +26,55 @@ export class OAuth2ExchangeInput {
code!: string;
@ApiProperty({
description: "The client secret (required for confidential clients)",
required: false,
description: "The redirect URI used in the authorization request",
example: "https://example.com/callback",
})
@IsOptional()
@IsString()
clientSecret?: string;
redirect_uri!: string;
@ApiProperty({
description: "The client secret for confidential clients",
})
@IsString()
client_secret!: string;
}
export class OAuth2ExchangePublicInput {
@ApiProperty({
description: "The client identifier",
example: "my-client-id",
})
@IsString()
client_id!: string;
@ApiProperty({
description: "The grant type — must be 'authorization_code'",
example: "authorization_code",
enum: ["authorization_code"],
})
@IsString()
@Equals("authorization_code")
grant_type!: "authorization_code";
@ApiProperty({
description: "The authorization code received from the authorize endpoint",
example: "abc123",
})
@IsString()
code!: string;
@ApiProperty({
description: "The redirect URI used in the authorization request",
example: "https://example.com/callback",
})
@IsString()
redirectUri!: string;
@ApiHideProperty()
@IsString()
@Equals("authorization_code")
grantType: string = "authorization_code";
redirect_uri!: string;
@ApiProperty({
description: "PKCE code verifier (required if code_challenge was used)",
required: false,
description: "PKCE code verifier (required for public clients that used code_challenge)",
})
@IsOptional()
@IsString()
codeVerifier?: string;
code_verifier!: string;
}
export type OAuth2ExchangeInput = OAuth2ExchangeConfidentialInput | OAuth2ExchangePublicInput;
@@ -1,24 +1,60 @@
import { ApiHideProperty, ApiProperty } from "@nestjs/swagger";
import { Equals, IsOptional, IsString } from "class-validator";
import { ApiProperty } from "@nestjs/swagger";
import { Equals, IsString } from "class-validator";
export class OAuth2RefreshConfidentialInput {
@ApiProperty({
description: "The client identifier",
example: "my-client-id",
})
@IsString()
client_id!: string;
@ApiProperty({
description: "The grant type — must be 'refresh_token'",
example: "refresh_token",
enum: ["refresh_token"],
})
@IsString()
@Equals("refresh_token")
grant_type!: "refresh_token";
export class OAuth2RefreshInput {
@ApiProperty({
description: "The refresh token",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
})
@IsString()
refreshToken!: string;
refresh_token!: string;
@ApiProperty({
description: "The client secret (required for confidential clients)",
required: false,
description: "The client secret for confidential clients",
})
@IsOptional()
@IsString()
clientSecret?: string;
client_secret!: string;
}
@ApiHideProperty()
export class OAuth2RefreshPublicInput {
@ApiProperty({
description: "The client identifier",
example: "my-client-id",
})
@IsString()
client_id!: string;
@ApiProperty({
description: "The grant type — must be 'refresh_token'",
example: "refresh_token",
enum: ["refresh_token"],
})
@IsString()
@Equals("refresh_token")
grantType: string = "refresh_token";
grant_type!: "refresh_token";
@ApiProperty({
description: "The refresh token",
example: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
})
@IsString()
refresh_token!: string;
}
export type OAuth2RefreshInput = OAuth2RefreshConfidentialInput | OAuth2RefreshPublicInput;
@@ -0,0 +1,107 @@
import type { PipeTransform } from "@nestjs/common";
import { HttpStatus, Injectable } from "@nestjs/common";
import { plainToClass } from "class-transformer";
import type { ValidationError } from "class-validator";
import { validateSync } from "class-validator";
import { OAuth2ExchangeConfidentialInput, OAuth2ExchangePublicInput } from "./exchange.input";
import { OAuth2RefreshConfidentialInput, OAuth2RefreshPublicInput } from "./refresh.input";
import { OAuth2HttpException } from "@/modules/auth/oauth2/filters/oauth2-http.exception";
export type OAuth2TokenInput =
| OAuth2ExchangeConfidentialInput
| OAuth2ExchangePublicInput
| OAuth2RefreshConfidentialInput
| OAuth2RefreshPublicInput;
@Injectable()
export class OAuth2TokenInputPipe implements PipeTransform {
// eslint-disable-next-line @typescript-eslint/no-empty-function
constructor() {}
transform(value: OAuth2TokenInput): OAuth2TokenInput {
if (!value) {
this.throwOAuthError("Body is required");
}
if (typeof value !== "object") {
this.throwOAuthError("Body should be an object");
}
const raw = value as unknown as Record<string, unknown>;
if (!raw.client_id || typeof raw.client_id !== "string") {
this.throwOAuthError("client_id is required");
}
const grantType = raw.grant_type;
if (grantType === "authorization_code") {
return this.validateExchange(value);
}
if (grantType === "refresh_token") {
return this.validateRefresh(value);
}
this.throwOAuthError("grant_type must be 'authorization_code' or 'refresh_token'");
}
private validateExchange(
value: OAuth2TokenInput
): OAuth2ExchangeConfidentialInput | OAuth2ExchangePublicInput {
if (this.isConfidentialExchange(value)) {
return this.validate(OAuth2ExchangeConfidentialInput, value);
}
return this.validate(OAuth2ExchangePublicInput, value);
}
private validateRefresh(
value: OAuth2TokenInput
): OAuth2RefreshConfidentialInput | OAuth2RefreshPublicInput {
if (this.isConfidentialRefresh(value)) {
return this.validate(OAuth2RefreshConfidentialInput, value);
}
return this.validate(OAuth2RefreshPublicInput, value);
}
private validate<T extends object>(cls: new () => T, value: OAuth2TokenInput): T {
const object = plainToClass(cls, value);
const errors = validateSync(object, {
whitelist: true,
forbidNonWhitelisted: true,
skipMissingProperties: false,
});
if (errors.length > 0) {
this.throwOAuthError(this.formatErrors(errors));
}
return object;
}
private formatErrors(errors: ValidationError[]): string {
return errors
.map((err) => {
const constraints = err.constraints ? Object.values(err.constraints).join(", ") : "";
const childrenErrors =
err.children && err.children.length > 0 ? `${this.formatErrors(err.children)}` : "";
return `${err.property} property is wrong,${constraints} ${childrenErrors}`;
})
.join(", ");
}
private isConfidentialExchange(value: OAuth2TokenInput): value is OAuth2ExchangeConfidentialInput {
return "client_secret" in value;
}
private isConfidentialRefresh(value: OAuth2TokenInput): value is OAuth2RefreshConfidentialInput {
return "client_secret" in value;
}
private throwOAuthError(description: string): never {
throw new OAuth2HttpException(
{ error: "invalid_request", error_description: description },
HttpStatus.BAD_REQUEST
);
}
}
@@ -1,10 +1,12 @@
import { Module } from "@nestjs/common";
import { oAuthServiceModule } from "@/lib/modules/oauth.module";
import { AtomsOAuth2Controller } from "@/modules/auth/oauth2/controllers/atoms-oauth2.controller";
import { OAuth2Controller } from "@/modules/auth/oauth2/controllers/oauth2.controller";
import { Module } from "@nestjs/common";
import { OAuth2ErrorService } from "@/modules/auth/oauth2/services/oauth2-error.service";
@Module({
imports: [oAuthServiceModule],
controllers: [OAuth2Controller, AtomsOAuth2Controller],
providers: [OAuth2ErrorService],
})
export class OAuth2Module {}
@@ -1,10 +1,9 @@
import { ERROR_STATUS, SUCCESS_STATUS } from "@calcom/platform-constants";
import { OAuthClientType } from "@calcom/prisma/enums";
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsBoolean, IsEnum, IsNotEmptyObject, IsOptional, IsString, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { OAuthClientType } from "@calcom/prisma/enums";
export class OAuth2ClientDto {
@ApiProperty({
description: "The OAuth client ID",
@@ -12,15 +11,15 @@ export class OAuth2ClientDto {
})
@IsString()
@Expose({ name: "clientId" })
id!: string;
client_id!: string;
@ApiProperty({
description: "The redirect URI for the OAuth client",
example: "https://example.com/callback",
})
@IsString()
@Expose()
redirectUri!: string;
@Expose({ name: "redirectUri" })
redirect_uri!: string;
@ApiProperty({
description: "The name of the OAuth client",
@@ -44,8 +43,8 @@ export class OAuth2ClientDto {
example: false,
})
@IsBoolean()
@Expose()
isTrusted!: boolean;
@Expose({ name: "isTrusted" })
is_trusted!: boolean;
@ApiProperty({
description: "The type of OAuth client (CONFIDENTIAL or PUBLIC)",
@@ -54,7 +53,7 @@ export class OAuth2ClientDto {
})
@IsEnum(OAuthClientType)
@Expose({ name: "clientType" })
type!: OAuthClientType;
client_type!: OAuthClientType;
}
export class OAuth2ClientResponseDto {
@@ -1,8 +1,6 @@
import { ApiProperty } from "@nestjs/swagger";
import { Expose, Type } from "class-transformer";
import { IsEnum, IsNotEmptyObject, IsNumber, IsString, ValidateNested } from "class-validator";
import { SUCCESS_STATUS, ERROR_STATUS } from "@calcom/platform-constants";
import { Expose } from "class-transformer";
import { IsNumber, IsString } from "class-validator";
export class OAuth2TokensDto {
@ApiProperty({
@@ -37,19 +35,3 @@ export class OAuth2TokensDto {
@Expose({ name: "expiresIn" })
expires_in!: number;
}
export class OAuth2TokensResponseDto {
@ApiProperty({ example: SUCCESS_STATUS, enum: [SUCCESS_STATUS, ERROR_STATUS] })
@IsEnum([SUCCESS_STATUS, ERROR_STATUS])
@Expose()
status!: typeof SUCCESS_STATUS | typeof ERROR_STATUS;
@ApiProperty({
type: OAuth2TokensDto,
})
@IsNotEmptyObject()
@ValidateNested()
@Type(() => OAuth2TokensDto)
@Expose()
data!: OAuth2TokensDto;
}
@@ -0,0 +1,72 @@
import { ErrorWithCode, getHttpStatusCode } from "@calcom/platform-libraries/errors";
import { HttpException, Injectable, InternalServerErrorException, Logger } from "@nestjs/common";
import { OAuthService } from "@/lib/services/oauth.service";
import { OAuth2HttpException } from "@/modules/auth/oauth2/filters/oauth2-http.exception";
import { OAuth2RedirectException } from "@/modules/auth/oauth2/filters/oauth2-redirect.exception";
const NON_REDIRECTABLE_REASONS = new Set([
"client_not_found",
"client_not_approved",
"redirect_uri_mismatch",
]);
@Injectable()
export class OAuth2ErrorService {
private readonly logger = new Logger("OAuth2ErrorService");
constructor(private readonly oAuthService: OAuthService) {}
handleAuthorizeError(err: unknown, redirectUri: string, state?: string): never {
if (err instanceof ErrorWithCode) {
const reason = err.data?.["reason"] as string | undefined;
if (reason && NON_REDIRECTABLE_REASONS.has(reason)) {
const statusCode = getHttpStatusCode(err);
throw new OAuth2HttpException(
{
error: err.message,
error_description: reason,
},
statusCode
);
}
}
const errorRedirectUrl = this.oAuthService.buildErrorRedirectUrl(redirectUri, err, state);
throw new OAuth2RedirectException(errorRedirectUrl);
}
handleTokenError(err: unknown): never {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
const reason = err.data?.["reason"] as string | undefined;
throw new OAuth2HttpException(
{
error: err.message,
error_description: reason ?? err.message,
},
statusCode
);
}
this.logger.error(err);
throw new OAuth2HttpException(
{
error: "server_error",
error_description: "An unexpected error occurred",
},
500
);
}
handleClientError(err: unknown, fallbackMessage: string): never {
if (err instanceof ErrorWithCode) {
const statusCode = getHttpStatusCode(err);
if (statusCode >= 500) {
this.logger.error(err);
}
throw new HttpException(err.message, statusCode);
}
this.logger.error(err);
throw new InternalServerErrorException(fallbackMessage);
}
}
@@ -1,3 +1,4 @@
import { getActiveUserBillingService } from "@calcom/platform-libraries/organizations";
import { getIncrementUsageIdempotencyKey, getIncrementUsageJobTag } from "@calcom/platform-libraries/tasker";
import { InjectQueue } from "@nestjs/bull";
import {
@@ -342,36 +343,13 @@ export class BillingService implements IBillingService, OnModuleDestroy {
invoiceStart: Date,
invoiceEnd: Date
): Promise<number> {
const managedUsersEmails =
await this.usersRepository.getOrgsManagedUserEmailsBySubscriptionId(subscriptionId);
if (!managedUsersEmails) return 0;
if (!invoiceStart || !invoiceEnd) {
this.logger.log("Invoice period start or end date is null");
return 0;
}
const activeManagedUserEmailsAsHost = await this.usersRepository.getActiveManagedUsersAsHost(
subscriptionId,
invoiceStart,
invoiceEnd
);
const activeHostEmails = activeManagedUserEmailsAsHost.map((email) => email.email);
const notActiveHostEmails = managedUsersEmails
.filter((email) => !activeHostEmails.includes(email.email))
.map((email) => email.email);
if (notActiveHostEmails.length === 0) return activeManagedUserEmailsAsHost.length;
const activeManagedUserEmailsAsAttendee = await this.usersRepository.getActiveManagedUsersAsAttendee(
notActiveHostEmails,
invoiceStart,
invoiceEnd
);
return activeManagedUserEmailsAsAttendee.length + activeManagedUserEmailsAsHost.length;
const activeUserBillingService = getActiveUserBillingService();
return activeUserBillingService.getActiveUserCountForPlatformOrg(subscriptionId, invoiceStart, invoiceEnd);
}
async updateStripeSubscriptionForTeam(teamId: number, plan: PlatformPlan): Promise<void> {
@@ -26,7 +26,7 @@ import {
Patch,
ParseIntPipe,
} from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiHeader, ApiOperation, ApiParam, ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToClass } from "class-transformer";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@@ -84,6 +84,7 @@ export class EventTypeWebhooksController {
@Get("/:webhookId")
@ApiOperation({ summary: "Get a webhook" })
@ApiParam({ name: "webhookId", type: String, required: true })
async getEventTypeWebhook(@GetWebhook() webhook: Webhook): Promise<EventTypeWebhookOutputResponseDto> {
return {
status: SUCCESS_STATUS,
@@ -116,6 +117,7 @@ export class EventTypeWebhooksController {
@Delete("/:webhookId")
@ApiOperation({ summary: "Delete a webhook" })
@ApiParam({ name: "webhookId", type: String, required: true })
async deleteEventTypeWebhook(@GetWebhook() webhook: Webhook): Promise<EventTypeWebhookOutputResponseDto> {
await this.webhooksService.deleteWebhook(webhook.id);
return {
@@ -3,7 +3,7 @@ import { MembershipRole } from "@calcom/platform-libraries";
import { SkipTakePagination } from "@calcom/platform-types";
import type { Webhook } from "@calcom/prisma/client";
import { Body, Controller, Delete, Get, Param, Patch, Post, Query, UseGuards } from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiHeader, ApiOperation, ApiParam, ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToClass } from "class-transformer";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { MembershipRoles } from "@/modules/auth/decorators/roles/membership-roles.decorator";
@@ -94,6 +94,7 @@ export class OAuthClientWebhooksController {
summary: "Get a webhook",
description: `<Warning>These endpoints are deprecated and will be removed in the future.</Warning>`,
})
@ApiParam({ name: "webhookId", type: String, required: true })
@UseGuards(IsOAuthClientWebhookGuard)
async getOAuthClientWebhook(@GetWebhook() webhook: Webhook): Promise<OAuthClientWebhookOutputResponseDto> {
return {
@@ -135,6 +136,7 @@ export class OAuthClientWebhooksController {
summary: "Delete a webhook",
description: `<Warning>These endpoints are deprecated and will be removed in the future.</Warning>`,
})
@ApiParam({ name: "webhookId", type: String, required: true })
@UseGuards(IsOAuthClientWebhookGuard)
async deleteOAuthClientWebhook(
@GetWebhook() webhook: Webhook
@@ -139,7 +139,7 @@ describe("Organizations Delegation Credentials Endpoints", () => {
data: {
workspacePlatformId: workspacePlatform.id,
organizationId: org.id,
domain: "@test-domain.com",
domain: "test-domain.com",
serviceAccountKey: encryptedServiceAccountKey,
enabled: false,
},
@@ -194,7 +194,7 @@ describe("Organizations Delegation Credentials Endpoints", () => {
expect(responseBody.status).toEqual(SUCCESS_STATUS);
expect(responseBody.data.enabled).toEqual(true);
expect(ensureDefaultCalendarsSpy).toHaveBeenCalledWith(org.id, "@test-domain.com");
expect(ensureDefaultCalendarsSpy).toHaveBeenCalledWith(org.id, "test-domain.com");
});
it("should not call ensureDefaultCalendars when disabling delegation credentials", async () => {
@@ -37,7 +37,7 @@ export class OrganizationsDelegationCredentialRepository {
},
where: {
organizationId: orgId,
user: { email: { endsWith: domain } },
user: { email: { endsWith: `@${domain}`, mode: "insensitive" } },
},
});
}
@@ -172,7 +172,7 @@ describe("OrganizationsDelegationCredentialService", () => {
await service.ensureDefaultCalendarsForUser(orgId, userId, userEmail);
expect(mockRepository.findEnabledByOrgIdAndDomain).toHaveBeenCalledWith(orgId, "@example.com");
expect(mockRepository.findEnabledByOrgIdAndDomain).toHaveBeenCalledWith(orgId, "example.com");
expect(mockQueue.add).toHaveBeenCalledWith(
DEFAULT_CALENDARS_JOB,
{ userId },
@@ -198,7 +198,7 @@ describe("OrganizationsDelegationCredentialService", () => {
await service.ensureDefaultCalendarsForUser(orgId, userId, userEmail);
expect(mockRepository.findEnabledByOrgIdAndDomain).toHaveBeenCalledWith(orgId, "@example.com");
expect(mockRepository.findEnabledByOrgIdAndDomain).toHaveBeenCalledWith(orgId, "example.com");
expect(mockQueue.add).not.toHaveBeenCalled();
});
@@ -174,7 +174,7 @@ export class OrganizationsDelegationCredentialService {
this.logger.warn(`Invalid email format for user ${userId}: missing domain`);
return;
}
const emailDomain = `@${emailParts[1]}`;
const emailDomain = emailParts[1];
const delegationCredential =
await this.organizationsDelegationCredentialRepository.findEnabledByOrgIdAndDomain(
@@ -1,6 +1,7 @@
import { OrganizationsWebhooksRepository } from "@/modules/organizations/webhooks/organizations-webhooks.repository";
import { UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
import { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
import { validateWebhookUrl, validateWebhookUrlIfChanged } from "@/modules/webhooks/utils/validate-webhook-url";
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
import { ConflictException, Injectable, NotFoundException } from "@nestjs/common";
@@ -12,6 +13,8 @@ export class OrganizationsWebhooksService {
) {}
async createWebhook(orgId: number, body: PipedInputWebhookType) {
validateWebhookUrl(body.subscriberUrl);
const existingWebhook = await this.organizationsWebhooksRepository.findWebhookByUrl(
orgId,
body.subscriberUrl
@@ -40,6 +43,8 @@ export class OrganizationsWebhooksService {
}
async updateWebhook(webhookId: string, body: UpdateWebhookInputDto) {
const existingSubscriberUrl = await this.webhooksRepository.getWebhookSubscriberUrl(webhookId);
validateWebhookUrlIfChanged(body.subscriberUrl, existingSubscriberUrl);
return this.webhooksRepository.updateWebhook(webhookId, body);
}
}
@@ -515,7 +515,7 @@ describe("Slots 2024-04-15 Endpoints", () => {
it("should do a booking for seated event and slot should show attendees count and bookingUid", async () => {
const startTime = "2050-09-05T11:00:00.000Z";
const booking = await bookingsRepositoryFixture.create({
uid: `booking-uid-${seatedEventTypeId}`,
uid: `booking-uid-seated-${seatedEventTypeId}-${randomString()}`,
title: "booking title",
startTime,
endTime: "2050-09-05T12:00:00.000Z",
@@ -549,7 +549,7 @@ describe("Slots 2024-04-15 Endpoints", () => {
});
bookingSeatsRepositoryFixture.create({
referenceUid: "100",
referenceUid: `seat-${randomString()}`,
data: {},
booking: {
connect: {
@@ -598,7 +598,7 @@ describe("Slots 2024-04-15 Endpoints", () => {
it("should do a booking for seated event and slot should show attendees count and bookingUid in range format", async () => {
const startTime = "2050-09-05T11:00:00.000Z";
const booking = await bookingsRepositoryFixture.create({
uid: `booking-uid-${seatedEventTypeId}`,
uid: `booking-uid-seated-${seatedEventTypeId}-${randomString()}`,
title: "booking title",
startTime,
endTime: "2050-09-05T12:00:00.000Z",
@@ -632,7 +632,7 @@ describe("Slots 2024-04-15 Endpoints", () => {
});
bookingSeatsRepositoryFixture.create({
referenceUid: "100",
referenceUid: `seat-${randomString()}`,
data: {},
booking: {
connect: {
@@ -832,7 +832,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
it("should do a booking for seated event and slot should show attendees count and bookingUid", async () => {
const startTime = "2050-09-05T11:00:00.000Z";
const booking = await bookingsRepositoryFixture.create({
uid: `booking-uid-${seatedEventType.id}`,
uid: `booking-uid-seated-${seatedEventType.id}-${randomString()}`,
title: "booking title",
startTime,
endTime: "2050-09-05T12:00:00.000Z",
@@ -866,7 +866,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
});
bookingSeatsRepositoryFixture.create({
referenceUid: "100",
referenceUid: `seat-${randomString()}`,
data: {},
booking: {
connect: {
@@ -961,7 +961,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
it("should do a booking for seated event and slot should show attendees count and bookingUid and return range format", async () => {
const startTime = "2050-09-05T11:00:00.000Z";
const booking = await bookingsRepositoryFixture.create({
uid: `booking-uid-${seatedEventType.id}`,
uid: `booking-uid-seated-range-${seatedEventType.id}-${randomString()}`,
title: "booking title",
startTime,
endTime: "2050-09-05T12:00:00.000Z",
@@ -995,7 +995,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
});
bookingSeatsRepositoryFixture.create({
referenceUid: "100",
referenceUid: `seat-${randomString()}`,
data: {},
booking: {
connect: {
@@ -1348,7 +1348,8 @@ describe("Slots 2024-09-04 Endpoints", () => {
advanceTo(newDate);
const slotDuration = 60;
const slotStartTime = "2050-09-05T10:00:00.000Z";
// Use 2050-09-06 to avoid overlap with other tests that reserve 2050-09-05
const slotStartTime = "2050-09-06T09:00:00.000Z";
const reserveResponse = await request(app.getHttpServer())
.post(`/v2/slots/reservations`)
.send({
@@ -1377,7 +1378,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
const response = await request(app.getHttpServer())
.get(
`/v2/slots?eventTypeId=${variableLengthEventType.id}&start=2050-09-05&end=2050-09-09&duration=60`
`/v2/slots?eventTypeId=${variableLengthEventType.id}&start=2050-09-05&end=2050-09-10&duration=60`
)
.set(CAL_API_VERSION_HEADER, VERSION_2024_09_04)
.expect(200);
@@ -1390,10 +1391,10 @@ describe("Slots 2024-09-04 Endpoints", () => {
const days = Object.keys(slots);
expect(days.length).toEqual(5);
const expectedSlotsUTC2050_09_05 = expectedSlotsUTC["2050-09-05"].filter(
const expectedSlotsUTC2050_09_06 = expectedSlotsUTC["2050-09-06"].filter(
(slot) => slot.start !== slotStartTime
);
expect(slots).toEqual({ ...expectedSlotsUTC, "2050-09-05": expectedSlotsUTC2050_09_05 });
expect(slots).toEqual({ ...expectedSlotsUTC, "2050-09-06": expectedSlotsUTC2050_09_06 });
const dbSlot = await selectedSlotRepositoryFixture.getByUid(
responseReservedVariableSlot.reservationUid
@@ -1409,7 +1410,7 @@ describe("Slots 2024-09-04 Endpoints", () => {
});
it("request slot contains already existing reserved slot", async () => {
// Try to reserve 9:45-12:45 when 10:00-11:00 is taken
// Try to reserve 8:45-11:45 when 09:00-10:00 on 2050-09-06 is taken
const newSlotStart = DateTime.fromISO(responseReservedVariableSlot.slotStart)
.minus({ minutes: 15 })
.toISO();
@@ -13,7 +13,7 @@ import {
Query,
UseGuards,
} from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiHeader, ApiOperation, ApiParam, ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToClass } from "class-transformer";
import { API_VERSIONS_VALUES } from "@/lib/api-versions";
import { API_KEY_HEADER } from "@/lib/docs/headers";
@@ -87,6 +87,7 @@ export class TeamsEventTypesWebhooksController {
@Get("/:webhookId")
@ApiOperation({ summary: "Get a webhook for a team event type" })
@ApiParam({ name: "webhookId", type: String, required: true })
@Roles("TEAM_MEMBER")
async getTeamEventTypeWebhook(@GetWebhook() webhook: Webhook): Promise<EventTypeWebhookOutputResponseDto> {
return {
@@ -122,6 +123,7 @@ export class TeamsEventTypesWebhooksController {
@Delete("/:webhookId")
@Roles("TEAM_ADMIN")
@ApiOperation({ summary: "Delete a webhook for a team event type" })
@ApiParam({ name: "webhookId", type: String, required: true })
async deleteTeamEventTypeWebhook(
@GetWebhook() webhook: Webhook
): Promise<EventTypeWebhookOutputResponseDto> {
@@ -16,7 +16,7 @@ import { WebhookOutputPipe } from "@/modules/webhooks/pipes/WebhookOutputPipe";
import { UserWebhooksService } from "@/modules/webhooks/services/user-webhooks.service";
import { WebhooksService } from "@/modules/webhooks/services/webhooks.service";
import { Controller, Post, Body, UseGuards, Get, Param, Query, Delete, Patch } from "@nestjs/common";
import { ApiHeader, ApiOperation, ApiTags as DocsTags } from "@nestjs/swagger";
import { ApiHeader, ApiOperation, ApiParam, ApiTags as DocsTags } from "@nestjs/swagger";
import { plainToClass } from "class-transformer";
import { SUCCESS_STATUS } from "@calcom/platform-constants";
@@ -75,6 +75,7 @@ export class WebhooksController {
@Get("/:webhookId")
@ApiOperation({ summary: "Get a webhook" })
@ApiParam({ name: "webhookId", type: String, required: true })
@UseGuards(IsUserWebhookGuard)
async getWebhook(@GetWebhook() webhook: Webhook): Promise<UserWebhookOutputResponseDto> {
return {
@@ -1,4 +1,5 @@
import { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
import { validateWebhookUrl } from "@/modules/webhooks/utils/validate-webhook-url";
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
@@ -9,6 +10,8 @@ export class EventTypeWebhooksService {
constructor(private readonly webhooksRepository: WebhooksRepository) {}
async createEventTypeWebhook(eventTypeId: number, body: PipedInputWebhookType) {
validateWebhookUrl(body.subscriberUrl);
if (body.eventTriggers.includes(WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR)) {
throw new BadRequestException(
"DELEGATION_CREDENTIAL_ERROR trigger is only available for organization webhooks"
@@ -1,4 +1,5 @@
import { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
import { validateWebhookUrl } from "@/modules/webhooks/utils/validate-webhook-url";
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
import { ConflictException, Injectable } from "@nestjs/common";
@@ -7,6 +8,8 @@ export class OAuthClientWebhooksService {
constructor(private readonly webhooksRepository: WebhooksRepository) {}
async createOAuthClientWebhook(platformOAuthClientId: string, body: PipedInputWebhookType) {
validateWebhookUrl(body.subscriberUrl);
const existingWebhook = await this.webhooksRepository.getOAuthClientWebhookByUrl(
platformOAuthClientId,
body.subscriberUrl
@@ -1,6 +1,7 @@
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
import type { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
import { validateWebhookUrl } from "@/modules/webhooks/utils/validate-webhook-url";
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
@Injectable()
@@ -8,6 +9,8 @@ export class TeamEventTypeWebhooksService {
constructor(private readonly webhooksRepository: WebhooksRepository) {}
async createTeamEventTypeWebhook(eventTypeId: number, body: PipedInputWebhookType) {
validateWebhookUrl(body.subscriberUrl);
if (body.eventTriggers.includes(WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR)) {
throw new BadRequestException(
"DELEGATION_CREDENTIAL_ERROR trigger is only available for organization webhooks"
@@ -1,4 +1,5 @@
import { PipedInputWebhookType } from "@/modules/webhooks/pipes/WebhookInputPipe";
import { validateWebhookUrl } from "@/modules/webhooks/utils/validate-webhook-url";
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
import { BadRequestException, ConflictException, Injectable } from "@nestjs/common";
@@ -9,6 +10,8 @@ export class UserWebhooksService {
constructor(private readonly webhooksRepository: WebhooksRepository) {}
async createUserWebhook(userId: number, body: PipedInputWebhookType) {
validateWebhookUrl(body.subscriberUrl);
if (body.eventTriggers.includes(WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR)) {
throw new BadRequestException(
"DELEGATION_CREDENTIAL_ERROR trigger is only available for organization webhooks"
@@ -1,4 +1,5 @@
import { UpdateWebhookInputDto } from "@/modules/webhooks/inputs/webhook.input";
import { validateWebhookUrlIfChanged } from "@/modules/webhooks/utils/validate-webhook-url";
import { WebhooksRepository } from "@/modules/webhooks/webhooks.repository";
import { Injectable, NotFoundException } from "@nestjs/common";
@@ -7,6 +8,8 @@ export class WebhooksService {
constructor(private readonly webhooksRepository: WebhooksRepository) {}
async updateWebhook(webhookId: string, body: UpdateWebhookInputDto) {
const existingSubscriberUrl = await this.webhooksRepository.getWebhookSubscriberUrl(webhookId);
validateWebhookUrlIfChanged(body.subscriberUrl, existingSubscriberUrl);
return this.webhooksRepository.updateWebhook(webhookId, body);
}
@@ -0,0 +1,95 @@
import { BadRequestException } from "@nestjs/common";
// Mock the platform-libraries module
const mockValidateUrlForSSRFSync: jest.Mock = jest.fn();
jest.mock("@calcom/platform-libraries", () => ({
validateUrlForSSRFSync: (url: string) => mockValidateUrlForSSRFSync(url),
}));
import { validateWebhookUrl, validateWebhookUrlIfChanged } from "./validate-webhook-url";
describe("validateWebhookUrl", () => {
beforeEach(() => {
mockValidateUrlForSSRFSync.mockReset();
});
it("does not throw when URL is valid", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: true });
expect(() => validateWebhookUrl("https://example.com/webhook")).not.toThrow();
expect(mockValidateUrlForSSRFSync).toHaveBeenCalledWith("https://example.com/webhook");
});
it("throws BadRequestException when URL is invalid", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: false, error: "Private IP address" });
expect(() => validateWebhookUrl("https://127.0.0.1/webhook")).toThrow(BadRequestException);
expect(() => validateWebhookUrl("https://127.0.0.1/webhook")).toThrow(
"Webhook URL is not allowed: Private IP address"
);
});
it("includes error message from validation result", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: false, error: "Blocked hostname" });
expect(() => validateWebhookUrl("https://localhost/webhook")).toThrow(
"Webhook URL is not allowed: Blocked hostname"
);
});
it("handles validation result without error message", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: false });
expect(() => validateWebhookUrl("invalid-url")).toThrow(
"Webhook URL is not allowed: undefined"
);
});
});
describe("validateWebhookUrlIfChanged", () => {
beforeEach(() => {
mockValidateUrlForSSRFSync.mockReset();
});
it("validates URL when it is different from existing", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: true });
validateWebhookUrlIfChanged("https://new.com/webhook", "https://old.com/webhook");
expect(mockValidateUrlForSSRFSync).toHaveBeenCalledWith("https://new.com/webhook");
});
it("throws when new URL is different and invalid", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: false, error: "Only HTTPS URLs are allowed" });
expect(() =>
validateWebhookUrlIfChanged("http://new.com/webhook", "https://old.com/webhook")
).toThrow(BadRequestException);
});
it("does not validate when URL is unchanged", () => {
validateWebhookUrlIfChanged("https://same.com/webhook", "https://same.com/webhook");
expect(mockValidateUrlForSSRFSync).not.toHaveBeenCalled();
});
it("does not validate when new URL is undefined", () => {
validateWebhookUrlIfChanged(undefined, "https://existing.com/webhook");
expect(mockValidateUrlForSSRFSync).not.toHaveBeenCalled();
});
it("validates when existing URL is undefined and new URL is provided", () => {
mockValidateUrlForSSRFSync.mockReturnValue({ isValid: true });
validateWebhookUrlIfChanged("https://new.com/webhook", undefined);
expect(mockValidateUrlForSSRFSync).toHaveBeenCalledWith("https://new.com/webhook");
});
it("does not validate when both URLs are undefined", () => {
validateWebhookUrlIfChanged(undefined, undefined);
expect(mockValidateUrlForSSRFSync).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,18 @@
import { BadRequestException } from "@nestjs/common";
import { validateUrlForSSRFSync } from "@calcom/platform-libraries";
export function validateWebhookUrl(subscriberUrl: string): void {
const validation = validateUrlForSSRFSync(subscriberUrl);
if (!validation.isValid) {
throw new BadRequestException(`Webhook URL is not allowed: ${validation.error}`);
}
}
export function validateWebhookUrlIfChanged(
newSubscriberUrl: string | undefined,
existingSubscriberUrl: string | undefined
): void {
if (newSubscriberUrl && newSubscriberUrl !== existingSubscriberUrl) {
validateWebhookUrl(newSubscriberUrl);
}
}
@@ -49,6 +49,14 @@ export class WebhooksRepository {
});
}
async getWebhookSubscriberUrl(webhookId: string): Promise<string | undefined> {
const webhook = await this.dbRead.prisma.webhook.findFirst({
where: { id: webhookId },
select: { subscriberUrl: true },
});
return webhook?.subscriberUrl ?? undefined;
}
async getUserWebhooksPaginated(userId: number, skip: number, take: number) {
return this.dbRead.prisma.webhook.findMany({
where: { userId },
@@ -114,7 +114,11 @@ export class WorkflowsRepository {
) {
await updateWorkflow({
ctx: {
user: { ...user, locale: user?.locale ?? "en" },
user: {
...user,
locale: user?.locale ?? "en",
organizationId: user.profiles?.[0]?.organization?.id ?? null,
},
prisma: this.dbWrite.prisma as unknown as PrismaClient,
},
input: data,
@@ -132,7 +136,11 @@ export class WorkflowsRepository {
) {
await updateWorkflow({
ctx: {
user: { ...user, locale: user?.locale ?? "en" },
user: {
...user,
locale: user?.locale ?? "en",
organizationId: user.profiles?.[0]?.organization?.id ?? null,
},
prisma: this.dbWrite.prisma as unknown as PrismaClient,
},
input: data,
@@ -1,8 +1,7 @@
import { OAuthClientStatus, OAuthClientType } from "@calcom/prisma/enums";
import { TestingModule } from "@nestjs/testing";
import { PrismaReadService } from "@/modules/prisma/prisma-read.service";
import { PrismaWriteService } from "@/modules/prisma/prisma-write.service";
import { TestingModule } from "@nestjs/testing";
import { OAuthClientType } from "@calcom/prisma/enums";
export class OAuth2ClientRepositoryFixture {
private prismaReadClient: PrismaReadService["prisma"];
@@ -19,8 +18,10 @@ export class OAuth2ClientRepositoryFixture {
redirectUri: string;
clientSecret?: string;
clientType?: OAuthClientType;
status?: OAuthClientStatus;
logo?: string;
isTrusted?: boolean;
userId?: number;
}) {
return this.prismaWriteClient.oAuthClient.create({
data: {
@@ -29,12 +30,21 @@ export class OAuth2ClientRepositoryFixture {
redirectUri: data.redirectUri,
clientSecret: data.clientSecret,
clientType: data.clientType || OAuthClientType.CONFIDENTIAL,
status: data.status || OAuthClientStatus.APPROVED,
logo: data.logo,
isTrusted: data.isTrusted || false,
...(data.userId && { user: { connect: { id: data.userId } } }),
},
});
}
async updateStatus(clientId: string, status: OAuthClientStatus) {
return this.prismaWriteClient.oAuthClient.update({
where: { clientId },
data: { status },
});
}
async delete(clientId: string) {
return this.prismaWriteClient.oAuthClient.delete({
where: { clientId },
+1 -1
View File
@@ -1 +1 @@
export const TRIGGER_VERSION = '20260205.1';
export const TRIGGER_VERSION = '20260216.1';
@@ -3,7 +3,7 @@ import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { loadTranslations } from "@calcom/lib/server/i18n";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
@@ -5,7 +5,7 @@ import { generateMeetingMetadata } from "app/_utils";
import { headers, cookies } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { loadTranslations } from "@calcom/lib/server/i18n";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx, decodeParams } from "@lib/buildLegacyCtx";
@@ -3,7 +3,7 @@ import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { loadTranslations } from "@calcom/lib/server/i18n";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
@@ -5,7 +5,7 @@ import { _generateMetadata } from "app/_utils";
import { cookies, headers } from "next/headers";
import { getOrgFullOrigin } from "@calcom/features/ee/organizations/lib/orgDomains";
import { loadTranslations } from "@calcom/lib/server/i18n";
import { loadTranslations } from "@calcom/i18n/server";
import { BookingStatus } from "@calcom/prisma/enums";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
@@ -3,7 +3,7 @@ import withEmbedSsrAppDir from "app/WithEmbedSSR";
import type { PageProps as ServerPageProps } from "app/_types";
import { cookies, headers } from "next/headers";
import { loadTranslations } from "@calcom/lib/server/i18n";
import { loadTranslations } from "@calcom/i18n/server";
import { buildLegacyCtx } from "@lib/buildLegacyCtx";
import { getServerSideProps } from "@lib/org/[orgSlug]/[user]/[type]/getServerSideProps";

Some files were not shown because too many files have changed in this diff Show More