* feat: add comprehensive validation tests for event-types/[id] GET endpoint
- Add integration tests for complex validation scenarios
- Test locations, booking fields, metadata, and seats validation
- Test edge cases that could cause validation mismatches between validators and DB results
- Ensure API response structure matches schemaEventTypeReadPublic schema
- Successfully catch validation discrepancies like missing displayLocationPublicly and assignAllTeamMembers fields
Co-Authored-By: alex@cal.com <me@alexvanandel.com>
* fix: add explicit type annotations for booking fields find callbacks
- Fix TypeScript errors on lines 388 and 395
- Provide proper type annotations for find method callback parameters
- Replace any[] with specific { label: string; value: string }[] type
- Ensure CI type checking passes
Co-Authored-By: alex@cal.com <me@alexvanandel.com>
* feat: convert event-types integration test to use real database
- Replace prismaMock with real Prisma client operations
- Create actual database records for comprehensive test scenarios
- Add proper setup/teardown with unique timestamps for test isolation
- Maintain all existing validation test coverage
- Follow Cal.com integration test patterns for database operations
Co-Authored-By: alex@cal.com <me@alexvanandel.com>
* feat: restore original mock-based test alongside integration test
- Restored original _get.test.ts with prismaMock for unit testing
- Kept _get.integration.test.ts with real database for integration testing
- Both tests provide complementary coverage: mocks for fast unit tests, real DB for validation testing
- Fixed type annotations in find callbacks to maintain type safety
Co-Authored-By: alex@cal.com <me@alexvanandel.com>
* fix: rename integration test to use proper naming convention
- Rename _get.integration.test.ts to _get.integration-test.ts
- Follows Cal.com vitest workspace pattern for integration tests
- Ensures integration test runs in proper CI workflow with database setup
Co-Authored-By: alex@cal.com <me@alexvanandel.com>
* fix: update tests to use handler return value instead of res._getData()
Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>
* fix: add proper type assertions for locations and bookingFields in tests
Co-Authored-By: unknown <>
* fix: create schedule for test user to fix foreign key constraint in integration tests
Co-Authored-By: unknown <>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: keith@cal.com <keithwillcode@gmail.com>
2026-01-12 12:01:43 +00:00
Hariom BalharaGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* chore: Integrate booking confirmation booking audit
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* fix: Use BookingStatus type instead of string for booking.status
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* Make booking-audit integration test utils reusable
* refactor: enhance handlePaymentSuccess to accept appSlug and actor identification
- Updated handlePaymentSuccess function to accept an object with paymentId, bookingId, appSlug, and traceContext.
- Introduced getActor function to determine the actor based on appSlug and credentialId.
- Modified webhook handlers for Alby, BTCPayServer, HitPay, PayPal, and Stripe to pass the new parameters.
- Improved logging for missing credentialId in payment processing.
- Adjusted related schemas to ensure proper type handling for booking status and actor identification.
* fix: Correct import paths and getActor function call
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* fix: Use ActorIdentification type instead of AuditActor in getActor
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* fix: Add guard clause for undefined actor in fireBookingAcceptedEvent
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* fix: Add actionSource to all confirm calls
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* refactor: Integrate actor identification and action source updates across booking services
- Added `makeUserActor` to various booking service files to enhance actor identification.
- Updated action source handling in booking confirmation and related functions to include "MAGIC_LINK".
- Refactored schemas to accommodate new actor and action source requirements, ensuring consistent type handling.
- Improved error handling and logging for booking actions to enhance traceability.
* Remvoe formatting changes
* Add test
* refactor: Enhance booking confirmation tests and event handling
- Updated `confirm.handler.test.ts` to improve test coverage for booking acceptance and rejection scenarios, including bulk bookings.
- Refactored the mock implementation of `BookingEventHandlerService` to streamline event handling for accepted and rejected bookings.
- Adjusted the `handleConfirmation` function to utilize `acceptedBookings` for better clarity and maintainability.
- Added tests to ensure correct invocation of event handler methods for both single and bulk booking confirmations and rejections.
* fix tests
* refactor: Use confirmHandler directly in link and verify-booking-token routes
Refactors the link and verify-booking-token API routes to call confirmHandler directly instead of using the tRPC caller pattern. This simplifies the code by removing the need for session getter, legacy request building, and context creation.
Changes:
- apps/web/app/api/link/route.ts: Use confirmHandler directly with ctx and input
- apps/web/app/api/verify-booking-token/route.ts: Use confirmHandler directly with ctx and input
- Updated tests to mock confirmHandler instead of tRPC caller
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* fix ts errors due to merge frommain
* feat: introduce getAppActor utility for actor creation
This commit adds a new utility function, getAppActor, to streamline the process of creating actor objects for apps based on their slug and credential ID. The function is integrated into handlePaymentSuccess and handleStripePaymentSuccess, replacing the previous inline actor creation logic. This refactor enhances code maintainability and readability by centralizing actor creation logic.
Changes:
- New file: packages/app-store/_utils/getAppActor.ts
- Updated handlePaymentSuccess and handleStripePaymentSuccess to use getAppActor
- Removed redundant actor creation code from these functions
* refactor: Update appSlug in payment success handlers to use appConfig.slug
This commit modifies the appSlug parameter in the handlePaymentSuccess function across multiple payment webhook handlers to utilize the appConfig.slug value instead of hardcoded strings. This change enhances consistency and maintainability of the code.
Changes:
- Updated appSlug in handlePaymentSuccess for btcpayserver, hitpay, and paypal webhooks.
- Adjusted a test case to reflect the new appSlug value for consistency.
* test: Enhance booking token verification and audit action tests
This commit adds additional assertions to the booking token verification tests to ensure that the confirmHandler is not called when an error occurs. It also introduces a mechanism to clean up additional booking UIDs after each test in the accepted action integration tests, improving test reliability. Furthermore, it updates the action source schema comment for clarity.
Changes:
- Updated tests in `verify-booking-token` to check that `mockConfirmHandler` is not called on error.
- Implemented cleanup logic for additional booking UIDs in `accepted-action.integration-test.ts`.
- Clarified comment in `actionSource.ts` regarding the schema for action sources.
- Refactored `handleConfirmation.ts` and `confirm.handler.ts` to include tracing logger for error handling in booking events.
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-12 08:17:26 -03:00
Hariom BalharaGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* chore: Integrate add guests booking audit
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* chore: Add actionSource parameter to support API_V2 audit logging
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
* refactor: update attendee audit action service to use new email schema
- Modified the `AttendeeAddedAuditActionService` to replace the old attendees schema with a new `emailSchema` for better validation.
- Adjusted the `addGuestsHandler` to pass the action source explicitly and updated the audit logging to reflect the new structure.
- Cleaned up the code for better readability and consistency.
* test: add happy path integration test for attendee added action
Co-Authored-By: hariom@cal.com <hariombalhara@gmail.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(api): remove OAuth client ID suffix from email in booking API responses
Fixes#25494 | Linear: CAL-6843
When managed users create or receive bookings, their emails were being returned with an internal OAuth client ID suffix (e.g., bob+cuid123@example.com). This suffix is used internally for user identification but should not be exposed in API responses.
Changes:
- Add cleanOAuthEmailSuffix() helper using CUID regex pattern
- Clean email suffix in hosts[], attendees[], bookingFieldsResponses.email, bookingFieldsResponses.guests[], and reassignedTo.email
- Pattern consistent with google-calendar.service.ts implementation
Affected output methods:
- getOutputBooking
- getOutputRecurringBooking
- getOutputSeatedBooking
- getOutputRecurringSeatedBooking
- getOutputReassignedBooking
- getHost
* refactor(api): preserve original email, add displayEmail field
Per team discussion, keep original email unchanged to avoid breaking changes for platform customers.
Add displayEmail field with CUID suffix removed for display purposes
* feat(api): add displayEmail to booking output DTOs
Add displayEmail property to BookingAttendee, BookingHost and ReassignedToDto for API documentation and type safety
* test(api): add e2e tests for displayEmail fields in managed user bookings
Add tests to verify that displayEmail fields correctly strip CUID suffix from OAuth managed user emails in booking API responses:
- Test host displayEmail returns email without CUID suffix
- Test attendee displayEmail returns email without CUID suffix
- Test bookingFieldsResponses.displayEmail returns clean email
- Test displayGuests array returns emails without CUID suffix
* false positive breaking change
* false positive breaking change
* test(api): update existing e2e tests to expect displayEmail field
* fix(api): add missing displayEmail to seated booking test assertions
The seated booking tests were missing displayEmail in the attendee
assertions for the second booking test and cancel-as-host test,
causing CI test failures
---------
Co-authored-by: cal.com <morgan@cal.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
* fix: improve cleanup for managed event types in e2e tests
- Add deleteAllUserEventTypes method to EventTypesRepositoryFixture
- Update afterAll cleanup to delete user event types before deleting users
- This ensures child event types of managed event types are properly cleaned up
- Fixes flaky tests caused by incomplete cleanup between test runs
- Add explicit return types to fixture methods to satisfy lint rules
- Replace @ts-ignore with @ts-expect-error for better type safety
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(auth): add URL validation for organization logo fields
- Add URL validation utility for server-side fetched URLs
- Validate logo URLs in tRPC organization schema
- Validate logo URLs in API v2 team DTOs
- Add graceful fallback in logo route for invalid URLs
- Only allow HTTPS and image data URLs
- Add unit tests for URL validation
* fix: add missing IP range and type validation
- Add RFC 6598 CGNAT range (100.64.0.0/10) to blocked IPs
- Add @IsString() decorator before custom URL validators
- Add boundary tests for new IP range
* fix: address review feedback
- Export validateUrlForSSRFSync via @calcom/platform-libraries
- Fix nullable/optional order in Zod schema
* fix: block localhost hostname and explicit null check
- Add localhost to BLOCKED_HOSTNAMES for sync validation
- Use explicit null check (url == null) instead of falsy check
* fix: allow empty string in URL validation
* refactor: extract shared validation logic
- Extract validateUrlCore() to eliminate duplication between sync/async versions
- Add JSDoc to all exported functions for better discoverability
- Remove redundant comments that repeated function names
- Simplify existing comments to be more concise
* fix: reject empty strings in URL validator
Previously if (!url) allowed empty strings to bypass validation.
Now explicitly checks for null/undefined only
2026-01-08 22:03:54 +00:00
Anik Dhabal BabuGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: Add email verification requirement for API v1 and v2 email updates
- API v2 (/v2/me): Implement email verification check when updating primary email
- Store new email in metadata as emailChangeWaitingForVerification when verification is required
- Send verification email using sendChangeOfEmailVerification
- Allow immediate email change if new email is already a verified secondary email
- Add hasEmailBeenChanged and sendEmailVerification flags to response
- Add tests to verify email verification behavior
- Add findVerifiedSecondaryEmail method to UsersRepository
- Add PrismaFeaturesRepository to MeModule providers
- API v1 (/v1/users/{userId}): Implement same email verification logic
- Check if email-verification feature flag is enabled
- Store new email in metadata when verification is required
- Send verification email for unverified email changes
- Allow immediate change for verified secondary emails
- Preserve existing API v1 response format
- Test fixtures: Add createSecondaryEmail method to UserRepositoryFixture
This fixes the vulnerability where users could update their primary email
without verification via API endpoints.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* update
* update
* refactor: Extract business logic to MeService and add platform-managed bypass
- Create MeService with all business logic extracted from MeController
- Update MeController to delegate to MeService (thin controller pattern)
- Add PrismaWorkerModule to MeModule imports to provide PrismaWriteService
- Add isPlatformManaged bypass: platform-managed users can update email without verification
- Fix test cleanup to use delete by ID instead of email to avoid failures when email changes
- Remove hasEmailBeenChanged and sendEmailVerification response flags per reviewer feedback
- Add comprehensive documentation to @ApiOperation describing email verification behavior
- Update tests to remove flag assertions
Addresses PR comments:
- supalarry: Extract logic to service layer
- supalarry: Allow platform-managed users to update email without verification
- supalarry: Remove response flags and document behavior in @ApiOperation instead
- cubic-dev-ai: Fix module dependency for PrismaFeaturesRepository
- cubic-dev-ai: Fix test cleanup issue
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* docs: Simplify API operation description
Remove internal implementation details about metadata staging and shorten the description to focus on API consumer behavior.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* fix
* update
* update
* update
* remove comment
* addressed commit
* review addressed
* use repository
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* refactor: First high level changes to getUsersAvailability
* Fix usage of getUserAvailability where getUsersAvailability is unused
* Fix user.schema.ts in APIv2
* User handler did not provide initial data
* Small ts fixes
* Set user non-nullable in getTimezoneFromDelegatedCredential
* Small ts fixes, ensure consumers are aware its nonnullable
* Mode is defaulted to none
* Mode is defaulted to none, fix ts when directly using fn (temp)
2026-01-08 14:45:26 +00:00
MorganGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* test: add e2e test for workflow partial update time/timeUnit preservation
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: time and timeUnit partial update workflows api v2
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-08 09:26:55 -03:00
MorganGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: set attendeeSeatId in evt for seated booking reschedule emails
When an attendee reschedules a seated booking, the reschedule/cancel links
in emails were using bookingUid instead of seatUid after the first reschedule.
This was because evt.attendeeSeatId was not being set before sending the email.
This fix ensures that evt.attendeeSeatId is set to bookingSeat.referenceUid
so that the email links consistently use seatUid for seated bookings.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* test: add E2E test for seatUid preservation across multiple reschedules
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: use valid time slots within availability window for E2E test
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: make E2E test self-contained to avoid shared state issues
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: update E2E test to validate seatUid usability across reschedules
Co-Authored-By: morgan@cal.com <morgan@cal.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-08 14:15:40 +02:00
Volnei MunhozGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
* refactor: replace shouldServeCache with mode parameter for calendar cache control
Replace the boolean shouldServeCache parameter with a new CalendarFetchMode type
that can have values 'slots', 'overlay', and 'booking'. This provides better
control over when to serve cache vs relay on calendar providers.
- 'slots' mode: Check feature flags and use cache when available (for getting
actual calendar availability)
- 'overlay' mode: Don't use cache (for overlay calendar availability)
- 'booking' mode: Don't use cache (for booking confirmation)
- undefined: Same as 'slots' for backwards compatibility
The cache decision logic is now centralized in getCalendar.ts based on the mode
parameter.
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: update CalendarService.test.ts to use mode parameter
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* refactor: use shared GetAvailabilityParams type across all calendar services
- Import GetAvailabilityParams and GetAvailabilityWithTimeZonesParams from @calcom/types/Calendar
- Replace inline type definitions with shared types in all calendar service implementations
- Update BaseCalendarService, CalendarCacheWrapper, and CalendarTelemetryWrapper
- Ensures consistent typing and follows DRY principles
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add missing IntegrationCalendar import and update mock getAvailability signature
- Add IntegrationCalendar back to sendgrid CalendarService imports
- Update bookingScenario mock getAvailability to use typed params object
- Add listCalendars method to mock Calendar object
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: update test files to use typed params object for getAvailability methods
- Update CalendarCacheWrapper.test.ts to call getAvailability/getAvailabilityWithTimeZones with params object
- Update getCalendarsEvents.test.ts toHaveBeenCalledWith assertions to expect params object
- All 32 tests now pass
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* refactor: consolidate to single GetAvailabilityParams type for both getAvailability methods
- Remove GetAvailabilityWithTimeZonesParams, use GetAvailabilityParams for both methods
- Add mode parameter to getAvailabilityWithTimeZones calls
- Update wrapper classes to pass mode through to underlying calendar
- Update test files to include mode in getAvailabilityWithTimeZones calls and assertions
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* refactor: use EventBusyDate with optional timeZone for getAvailabilityWithTimeZones
- Add optional timeZone field to EventBusyDate type
- Update getAvailabilityWithTimeZones return type to use EventBusyDate[]
- Update Google Calendar service and wrapper classes to use the new type
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: type errors and remove unused calendar watching methods
- Fix type errors in CalendarCacheWrapper.ts (convert null to undefined for timeZone)
- Fix type errors in getCalendarsEvents.ts (ensure timeZone is always present)
- Remove unused watchCalendar/unwatchCalendar from Calendar interface
- Remove unused startWatchingCalendarsInGoogle/stopWatchingCalendarsInGoogle from GoogleCalendarService
- Remove unused imports (uuid, uniqueBy, GOOGLE_WEBHOOK_URL, ONE_MONTH_IN_MS)
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: remove watchCalendar/unwatchCalendar from CalendarTelemetryWrapper
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* refactor: remove verbose JSDoc param comments from wrapper classes
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* refactor: make mode parameter required in getCalendar
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add required mode parameter to all getCalendar callers
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: provide default mode value in getBusyCalendarTimes
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add mode parameter to remaining getCalendar callers
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add mode parameter to vital and wipemycalother reschedule
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add mode parameter to credential-sync API endpoint
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* refactor: add 'none' mode to CalendarFetchMode and use as default
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* test: add mode parameter to getCalendarsEvents test calls
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* Update packages/app-store/delegationCredential.ts
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>
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
2026-01-08 09:07:41 -03:00
Syed Ali ShahbazGitHubcubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
* fix: remove @calcom/web imports from packages/features to eliminate circular dependency
- Migrate UserTableUser and MemberPermissions types to packages/features/users/types/user-table.ts
- Migrate useGeo hook to packages/features/geo/GeoContext.tsx
- Migrate buildLegacyRequest to packages/lib/buildLegacyCtx.ts
- Migrate Calendar component to packages/features/calendars/weeklyview/components/
- Move test utilities (bookingScenario, fixtures) to packages/features/test/
- Update all imports in packages/features to use new locations
- Add re-exports in apps/web for backward compatibility
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: delete original implementation files and fix type issues
- Delete original calendar component files in apps/web (keep only re-export stubs)
- Migrate OutOfOfficeInSlots to packages/features/bookings/components
- Convert apps/web OutOfOfficeInSlots to re-export stub
- Fix className vs class issue in Calendar.tsx
- Fix @calcom/trpc import violation in user-table.ts by using structural type
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: add missing isGroup and contains fields to UserTableUser attributes type
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: update customRole type to match actual Prisma Role model
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix build
* fix
* fix
* cleanup weeklyview
* fix
* refactor to mv MemberPermissions to types package
* add types dependency to features
* fix
* fix
* fix
* fix
* fix
* fix
* rename
* rename
* migrate
* migrate
* migrate
* fix
* fix
* fix
* refactor: move test utilities from packages/features/test to tests/libs
- Move bookingScenario utilities to tests/libs/bookingScenario
- Move fixtures to tests/libs/fixtures
- Update all imports in packages/features test files to use new location
- Update all imports in apps/web test files to use new location
- Eliminates duplication of test utilities between packages/features and apps/web
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: correct relative import paths for tests/libs in test files
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* refactor: replace test utility implementations with re-exports to tests/libs
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: fix test import paths and move signup handler tests to apps/web
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: move buildLegacyCtx to packages/lib and restore handlers to packages/features
- Move buildLegacyCtx from apps/web/lib to packages/lib to break circular dependency
- Update apps/web/lib/buildLegacyCtx.ts to re-export from @calcom/lib
- Restore signup handlers and tests to packages/features/auth/signup/handlers
- Update handler imports to use @calcom/lib/buildLegacyCtx instead of @calcom/web/lib/buildLegacyCtx
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: update recurring-event.test.ts imports to use tests/libs path
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* refactor: delete test re-export files and update imports to use tests/libs directly
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: update remaining test imports to use tests/libs directly
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: update handleRecurringEventBooking calls to match function signature (1 arg)
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* remove
* migrate tests
* migrate tests
* refactor: update test mock imports by removing and using async for mock creators.
* fix type errors
* fix: add type assertion for MockUser in p2002.test-suite.ts
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: restore locale import in compareReminderBodyToTemplate.test.ts using relative path
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* feat: create @calcom/testing package and migrate tests from /tests directory
- Created new @calcom/testing package in /packages/testing
- Moved all files from /tests to /packages/testing
- Updated all imports across the codebase to use @calcom/testing alias
- Removed /tests directory at root level
This allows other packages like @calcom/features and @calcom/web to import
testing utilities using the @calcom/testing alias instead of relative paths.
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix
* fix
* fix: add missing useBookings export to @calcom/atoms package
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: add missing useCalendarsBusyTimes and useConnectedCalendars exports to @calcom/atoms
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* chore: add @calcom/testing as explicit devDependency to packages that use it
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* refactor: move setupVitest.ts into @calcom/testing package
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix
* chore: add biome rules to restrict @calcom/testing imports
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix
* rename libs to lib
* rename libs to lib
* add rule
* add rule
* refactor: remove @calcom/features imports from @calcom/testing
- Move mockPaymentSuccessWebhookFromStripe to fresh-booking.test.ts
- Replace ProfileRepository.generateProfileUid() with uuidv4()
- Clone Tracking type into @calcom/testing/src/lib/types.ts
- Update imports in expects.ts and getMockRequestDataForBooking.ts
- Move source files into src/ folder
- Move CalendarManager mock to @calcom/features
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* fix: add explicit exports for nested paths in @calcom/testing
Co-Authored-By: benny@cal.com <sldisek783@gmail.com>
* improve
* improve
* fix
* fix
* fix type checks
* fix type checks
* fix type checks
* fix tests
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat: api v2 add missing event type fields for advanced settings
Add 9 event type fields to API v2 that were available in tRPC but missing from the platform API:
- disableCancelling: disable cancelling for guests/organizer
- disableRescheduling: disable rescheduling for guests/organizer
- canSendCalVideoTranscriptionEmails: send Cal Video transcription emails
- autoTranslateInstantMeetingTitleEnabled: auto-translate instant meeting titles
- interfaceLanguage: preferred booking interface language
- allowReschedulingPastBookings: allow rescheduling past events
- allowReschedulingCancelledBookings: allow booking via reschedule link
- customReplyToEmail: custom reply-to email for confirmations
- showOptimizedSlots: optimize time slot arrangement
Updated output/input schemas, transformation services, and E2E tests.
* fix(api-v2): add proper OpenAPI types for nullable event type fields
Add explicit type and nullable properties to @ApiPropertyOptional decorators
for fields with `boolean | null` or `string | null` types. Without these,
Swagger was generating incorrect "type": "object" instead of the correct types.
Fixed fields:
- disableCancelling: type: Boolean, nullable: true
- disableRescheduling: type: Boolean, nullable: true
- interfaceLanguage: type: String, nullable: true
- allowReschedulingCancelledBookings: type: Boolean, nullable: true
- customReplyToEmail: type: String, nullable: true
- showOptimizedSlots: type: Boolean, nullable: true
* refactor: customReplyToEmail was intentionally excluded from this PR. The web UI
restricts this field to only allow the user's own verified emails via a
dropdown, but implementing the same validation in the API requires additional
business logic. This will be addressed in a separate PR with proper email
ownership validation.
* feat(api-v2): add validation for interfaceLanguage field
Add @IsIn validation to interfaceLanguage field to only accept supported
locales. This ensures API v2 matches the web UI behavior where users can
only select from a predefined dropdown of supported languages.
Changes:
- Add SUPPORTED_LOCALES constant to @calcom/platform-constants
- Add @IsIn([...SUPPORTED_LOCALES]) validation to create/update DTOs
- Add E2E tests for invalid locale rejection (400 error)
- Add cross-reference comments in i18n.json and api.ts to keep in sync
* docs(api): add default values to event type input field documentation
Added default value documentation to @DocsPropertyOptional decorators
for the new event type fields in API v2 (2024_06_14):
- disableCancelling: false
- disableRescheduling: false
- canSendCalVideoTranscriptionEmails: true
- autoTranslateInstantMeetingTitleEnabled: false
- allowReschedulingPastBookings: false
- allowReschedulingCancelledBookings: false
- showOptimizedSlots: false
This improves API documentation by clearly communicating default
values to API consumers in the OpenAPI spec.
* feat(api-v2): refactor event type settings to object types for future extensibility
- Convert disableRescheduling from boolean to object with disabled and minutesBefore properties
- Convert disableCancelling from boolean to object with disabled property
- Move canSendCalVideoTranscriptionEmails into CalVideoSettings as sendTranscriptionEmails
- Remove autoTranslateInstantMeetingTitleEnabled (Enterprise-only feature)
- Add DisableRescheduling_2024_06_14 and DisableCancelling_2024_06_14 input/output types
- Add transformation methods for new object types in input and output services
- Update E2E tests for new API contract
BREAKING CHANGE: disableRescheduling and disableCancelling now accept objects instead of booleans
* fix(api-v2): prevent clearing calVideoSettings when only sendTranscriptionEmails is provided
Only include calVideoSettings in transformed output if it has properties,
avoiding unintentional reset of existing settings during updates.
* feat(api-v2): add OAuth2 controller skeleton for auth module
- Add new OAuth2 module under /auth with controller, service, repository, and DTOs
- Implement skeleton endpoints:
- GET /v2/auth/oauth2/clients/:clientId - Get OAuth client info
- POST /v2/auth/oauth2/clients/:clientId/authorize - Generate authorization code
- POST /v2/auth/oauth2/clients/:clientId/exchange - Exchange code for tokens
- POST /v2/auth/oauth2/clients/:clientId/refresh - Refresh access token
- Create input DTOs for authorize, exchange, and refresh operations
- Create output DTOs for client info, authorization code, and tokens
- Register OAuth2Module in endpoints.module.ts
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* chore: add missing functions to platform libraries
* feat(api-v2): integrate OAuthService from platform-libraries into OAuth2 controller
- Add OAuthService export to platform-libraries
- Refactor OAuth2Service to use OAuthService.validateClient() and OAuthService.verifyPKCE()
- Remove duplicate local implementations of validateClient and verifyPKCE methods
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* feat(api-v2): use local validateClient and verifyPKCE implementations
- Remove OAuthService export from platform-libraries (will be deprecated)
- Reimplement validateClient and verifyPKCE methods locally in OAuth2Service
- Use verifyCodeChallenge and generateSecret from platform-libraries directly
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor(api-v2): separate repositories for OAuth2, access codes, and teams
- Create AccessCodeRepository for access code Prisma operations
- Add findTeamBySlugWithAdminRole method to TeamsRepository
- Move generateAuthorizationCode, createTokens, verifyRefreshToken to OAuth2Service
- Update OAuth2Repository to only contain OAuth client operations
- Update OAuth2Module to import TeamsModule and provide AccessCodeRepository
Addresses PR review comments to properly separate concerns
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* feat(api-v2): implement JWT token creation and verification for OAuth2
- Implement createTokens method using jsonwebtoken to sign access and refresh tokens
- Implement verifyRefreshToken method to verify JWT refresh tokens
- Add ConfigService injection for CALENDSO_ENCRYPTION_KEY access
- Import ConfigModule in OAuth2Module for dependency injection
Based on logic from apps/web/app/api/auth/oauth/token/route.ts and
apps/web/app/api/auth/oauth/refreshToken/route.ts
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: refactor and dayjs import fix
* feat(api-v2): add ApiAuthGuard to getClient endpoint and e2e tests for OAuth2
- Add @UseGuards(ApiAuthGuard) to getClient endpoint for authentication
- Add comprehensive e2e tests for all OAuth2 endpoints:
- GET /v2/auth/oauth2/clients/:clientId
- POST /v2/auth/oauth2/clients/:clientId/authorize
- POST /v2/auth/oauth2/clients/:clientId/exchange
- POST /v2/auth/oauth2/clients/:clientId/refresh
- Tests cover happy paths and error cases (invalid client, invalid code, etc.)
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* chore(api-v2): hide OAuth2 endpoints from Swagger documentation
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* hide endpoints from doc
* fix(api-v2): address PR feedback for OAuth2 controller
- Fix P0 critical bug: token_type field name mismatch in DecodedRefreshToken interface
- Add @Equals('authorization_code') validation to exchange.input.ts grantType
- Add @Equals('refresh_token') validation to refresh.input.ts grantType
- Add @IsNotEmpty() validation to get-client.input.ts clientId
- Add @Expose() decorators to all output DTOs for proper serialization
- Add security test assertion to verify clientSecret is not returned in response
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* feat(api-v2): implement redirect behavior for OAuth2 authorize endpoint
- Update authorize endpoint to return HTTP 303 redirect with authorization code
- Add exact match validation for redirect URI (security requirement)
- Implement error handling with redirect to redirect URI and error query params
- Add state parameter support for CSRF protection
- Update e2e tests to verify redirect behavior (303 status, Location header, error redirects)
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor(api-v2): address PR feedback for OAuth2 authorize endpoint
- Make redirectUri a required input parameter (remove optional fallback)
- Move buildRedirectUrl and mapErrorToOAuthError to oauth2Service
- Add return statements to res.redirect() calls
- Simplify controller by delegating redirect URL building to service
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* wip move code outside of api v2
* feat(oauth): wire up dependency injection for OAuthService and repositories
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* refactor: oAuthService used in routes
* fix imports
* fix(api-v2): return 404 for invalid client ID instead of redirect in authorize endpoint
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix(api-v2): fix E2E test URL paths and remove bootstrap() in authenticated section
- Remove bootstrap() call in authenticated section to match working test pattern
- Change URL paths from /api/v2/... to /v2/... in authenticated section
- Keep bootstrap() and /api/v2/... paths in unauthenticated section
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix(api-v2): mock getToken from next-auth/jwt for E2E tests
- Add jest.mock for next-auth/jwt getToken function
- Mock returns null for unauthenticated tests
- Mock returns { email: userEmail } for authenticated tests
- Remove withNextAuth helper since ApiAuthGuard uses ApiAuthStrategy
which calls getToken directly, not NextAuthStrategy
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix tests and code review
* cleanup generate secrets
* cleanup controller
* chore: remove console.log from OAuthService.validateClient
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* Update apps/web/app/api/auth/oauth/refreshToken/route.ts
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
* fix(api-v2): add bootstrap() to authenticated E2E tests and update URL paths to /api/v2/
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* Merge remote-tracking branch 'origin/devin/oauth2-controller-skeleton-1765988792' and remove console.log from token route
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* chore: remove dead code
* refactor
* refactor: generateAuthCode trpc handler and getClient trpc handler
* remove pkce check for refreshToken endpoint
* Update packages/trpc/server/routers/viewer/oAuth/getClient.handler.ts
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
* refactor: error handling
* refactor: error handling
* refactor: error handling
* remove console log
* provide redirectUri in generateAuthCodeHandler
* provide redirectUri in authorize view
* refactor: replace HttpError with ErrorWithCode in OAuth files
- Update OAuthService to use ErrorWithCode instead of HttpError
- Update mapErrorToOAuthError to check ErrorCode instead of status codes
- Update token/route.ts and refreshToken/route.ts to use ErrorWithCode
- Add ErrorWithCode export to platform-libraries
- Use getHttpStatusCode to map ErrorCode to HTTP status codes
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: update generateAuthCode handler to use ErrorWithCode instead of HttpError
The handler was still checking for HttpError in its catch block, but OAuthService
now throws ErrorWithCode. This caused the error messages to be lost and replaced
with 'server_error' instead of the specific error messages.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: update OAuth2 controller to use ErrorWithCode instead of HttpError
The controller was still checking for HttpError in its catch blocks, but OAuthService
now throws ErrorWithCode. This caused all errors to return 500 Internal Server Error
instead of the correct HTTP status codes (400, 401, 404).
Also added getHttpStatusCode export to platform-libraries.
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: add explicit unknown type annotation to catch blocks in OAuth2 controller
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: change NotFoundException to HttpException in authorize endpoint
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: handle err with ErrorWithCode in authorize endpoint catch block
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: move errorWithCode
* fix: error code rfc
* fix: no need to handle errors there is a middleware
* refactor errors
* refactor errors
* refactor redirecturi and state from api
* refactor: address PR comments for OAuth2 controller
- Remove unused GetOAuth2ClientInput class
- Change API tag from 'Auth / OAuth2' to 'OAuth2'
- Move OAuthClientFixture to separate fixture file (oauth2-client.repository.fixture.ts)
- Add 'type' property to OAuth2ClientDto for confidential/public client type
- Rename 'clientId' to 'id' in OAuth2ClientDto (using @Expose mapping)
- Clean up duplicate provider declarations in oauth2.module.ts
- Update e2e tests to use new fixture and verify type property
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.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>
Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: Volnei Munhoz <volnei.munhoz@gmail.com>
Co-authored-by: Volnei Munhoz <volnei@cal.com>
## What does this PR do?
> **⚠️ Note: This PR does not enable booking audit in production.** The `BookingAuditTaskerProducerService` has an [`IS_PRODUCTION` guard](https://github.com/calcom/cal.com/blob/integrate-booking-creation-reschedule-audit/packages/features/booking-audit/lib/service/BookingAuditTaskerProducerService.ts#L106-L108) that skips audit task queueing in production environments. This allows the integration to be tested in development before enabling it in production.
Integrates audit logging for booking cancellations, following the pattern established in PR #26046 for booking creation/rescheduling audit.
- Related to #25125 (Booking Audit Infrastructure)
### Changes:
- Add audit logging for single booking cancellation via `onBookingCancelled`
- Add audit logging for bulk recurring booking cancellation via `onBulkBookingsCancelled`
- Pass `userUuid` and `actionSource` from webapp cancel route (WEBAPP)
- Pass `userUuid` and `actionSource` from API-v2 bookings service (API_V2)
- Create `getAuditActor` helper to derive actor from userUuid or create synthetic guest actor
- Add `getUniqueIdentifier` helper for generating unique actor identifiers
- Add warning log when `actionSource` is "UNKNOWN" for observability
- Add integration tests for booking cancellation audit
### Audit Data Captured:
- `cancellationReason` (simple string value)
- `cancelledBy` (simple string value)
- `status` (old → new, e.g., "ACCEPTED" → "CANCELLED")
### Updates since last revision:
- Simplified `CancelledAuditActionService` schema: `cancellationReason` and `cancelledBy` are now stored as simple nullable strings instead of change objects (old/new), since cancellation is a one-time event where tracking previous values doesn't apply
- Added integration tests for cancelled booking audit in `booking-audit-cancelled.integration-test.ts`
- Added `getUniqueIdentifier` helper function in actor.ts for generating unique identifiers with prefixes
## 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](https://cal.com/docs). N/A - no documentation changes needed.
- [ ] I confirm automated tests are in place that prove my fix is effective or that my feature works.
## How should this be tested?
1. Cancel a single booking via the webapp - verify audit record is created with actor and actionSource="WEBAPP"
2. Cancel a single booking via API v2 - verify audit record is created with actionSource="API_V2"
3. Cancel all remaining bookings in a recurring series - verify bulk audit records are created with shared operationId
4. Cancel via unauthenticated cancel link - verify guest actor is created with synthetic email (prefixed with "param-" or "fallback-")
5. Run integration tests: `yarn test packages/features/booking-audit/lib/service/__tests__/booking-audit-cancelled.integration-test.ts`
## Human Review Checklist
- [ ] Verify `onBookingCancelled` and `onBulkBookingsCancelled` methods exist in `BookingEventHandlerService`
- [ ] Review the `getAuditActor` fallback logic - creates synthetic email with "fallback-" or "param-" prefix when no userUuid available
- [ ] Confirm the simplified schema for `cancellationReason`/`cancelledBy` (no longer tracking old→new) is intentional
- [ ] Note: Audit logging calls are awaited directly - if audit service fails, the cancellation will fail. Confirm this is the desired behavior.
- [ ] Verify `CancelledAuditDisplayData` type no longer includes `previousReason` and `previousCancelledBy` fields
---
Link to Devin run: https://app.devin.ai/sessions/42404e76a66946fe9e46fa07fb12e779
Requested by: @hariombalhara (hariom@cal.com)
Replace N sequential queries with single batch queries in:
- getOutputRecurringBookings
- getOutputRecurringSeatedBookings
Uses existing batch repository methods. Reduces database roundtrips
from O(n) to O(1) for recurring booking lookups
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
2026-01-07 08:41:09 +00:00
Eunjae LeeGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat: implement FeatureOptInService WIP
* clean up
* feat: consolidate feature repositories and add updateFeatureForUser
- Implement updateFeatureForUser in FeaturesRepository (similar to updateFeatureForTeam)
- Move getUserFeatureState and getTeamFeatureState from PrismaFeatureOptInRepository to FeaturesRepository
- Update FeatureOptInService to use only FeaturesRepository
- Add setUserFeatureState and setTeamFeatureState methods to FeatureOptInService
- Update _router.ts to remove PrismaFeatureOptInRepository usage
- Remove PrismaFeatureOptInRepository.ts and FeatureOptInRepositoryInterface.ts
- Update features.repository.interface.ts and features.repository.mock.ts
- Add integration tests for updateFeatureForUser, getUserFeatureState, getTeamFeatureState
- Update service.integration-test.ts to use FeaturesRepository
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* refactor: rename updateFeatureForUser to setUserFeatureState
Rename to match the convention used for setTeamFeatureState
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* refactor: return FeatureState type from getUserFeatureState and getTeamFeatureState
* fix integration tests
* clean up logics
* update services and router
* refactor: change getUserFeatureState and getTeamFeatureState to accept featureIds array
- Renamed getUserFeatureState to getUserFeatureStates
- Renamed getTeamFeatureState to getTeamFeatureStates
- Changed parameter from featureId: string to featureIds: string[]
- Changed return type from FeatureState to Record<string, FeatureState>
- Updated FeatureOptInService to use the new batch methods
- Added tests for querying multiple features in a single call
- Optimized listFeaturesForTeam to fetch all feature states in one query
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* feat: add getFeatureStateForTeams for batch querying multiple teams
- Added getFeatureStateForTeams method to query a single feature across multiple teams in one call
- Updated FeatureOptInService.resolveFeatureStateAcrossTeams to use the new batch method
- Replaces N+1 queries with a single database query for team states
- Added comprehensive integration tests for the new method
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* refactor: combine org and team state queries into single call
- Include orgId in the teamIds array passed to getFeatureStateForTeams
- Extract org state and team states from the combined result
- Reduces database queries from 3 to 2 in resolveFeatureStateAcrossTeams
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* refactor: use team.isOrganization and clarify computeEffectiveState comment
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* refactor: use MembershipRepository.findAllByUserId with isOrganization
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* feat: add featureId validation using isOptInFeature type guard
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* less queries
* add fallback value
* fix type error
* move files
* add autoOptInFeatures column
* use autoOptInFeatures flag within FeatureOptInService
* add setUserAutoOptIn and setTeamAutoOptIn
* fix computeEffectiveState logic
* rewrite computeEffectiveState
* clean up integration tests
* clean up in afterEach
* fix type error
* refactor: use FeaturesRepository methods instead of direct Prisma calls
Replace all manual userFeatures and teamFeatures Prisma operations with
the new setUserFeatureState and setTeamFeatureState repository methods.
Changes include:
- Admin handlers (assignFeatureToTeam, unassignFeatureFromTeam)
- Test fixtures and integration tests
- Playwright fixtures
- Development scripts
This ensures consistent feature flag management through the repository
pattern and supports the new tri-state semantics (enabled/disabled/inherit).
Co-Authored-By: eunjae@cal.com <hey@eunjae.dev>
* clean up
* fix the logic
* extract some logic into applyAutoOptIn()
* remove wrong code
* refactor: convert setUserFeatureState and setTeamFeatureState to object params with discriminated union
- Convert multiple positional parameters to single object parameter
- Use discriminated union types: assignedBy required for enabled/disabled, omitted for inherit
- Update all callers across repository, service, handlers, fixtures, and tests
* fix type error
* use Promise.all
* fix
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-01-06 16:55:53 +01:00
MorganGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* feat(api): add team event-types webhooks controller
- Add TeamsEventTypesWebhooksController for managing webhooks on team event types
- Add IsTeamEventTypeWebhookGuard for authorization
- Add TeamEventTypeWebhooksService for business logic
- Register new controller in TeamsEventTypesModule
- Enable unsafeParameterDecoratorsEnabled in biome.json for NestJS support
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* test(api): add e2e tests for team event-types webhooks controller
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix(api): restrict team event-type webhooks to admins/owners only
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix(api): use regular imports instead of type imports for DI and DTOs
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix(api): use regular imports for DI in guard file
Co-Authored-By: morgan@cal.com <morgan@cal.com>
* fix: circular depndency in modules
* delete teams in test
* fix roles guard
* fix biome
* fix guard
* resolve type import
* resolve review feedback
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
## What does this PR do?
Similar to #25721, adds uuid in session so that BookingAudit has it readily available
Adds the user's UUID to the booking metadata by:
1. Extending the NextAuth `User` interface to include an optional `uuid` property from PrismaUser
2. Making `uuid` required on `Session.user` via intersection type (`User & { uuid: PrismaUser["uuid"] }`)
3. Adding `uuid` to the session user object in `getServerSession.ts`
4. Adding `uuid` to the `AdapterUser` transformation in `next-auth-custom-adapter.ts`
5. Passing `userUuid` from the session to the booking creation flow
6. Updating the API key verification flow to include `uuid` in the user data (repository, service, and type definitions)
7. Adding `req.userUuid` as a required field on the request object (like `req.userId`)
8. Adding `uuid` to mock session objects in web app routes and test context
9. Adding `uuid` to the `findByEmailAndIncludeProfilesAndPassword` query in UserRepository
Also removes commented-out code that was placeholder for future work and fixes lint warnings for unused variables.
## 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](https://cal.com/docs). N/A - no documentation 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. Verify that the NextAuth session callback is already populating the `uuid` field on the user object
2. Create a booking and confirm `userUuid` is included in the booking metadata
3. Test API v1 endpoints (`/api/invites` POST and `/api/teams/[teamId]/publish`) to verify they receive the uuid from the authenticated user
4. Check that the booking flow works correctly with the new parameter
5. Test SAML login flow to verify session still works correctly (uuid is resolved from database after authentication)
## Human Review Checklist
- [ ] Verify the NextAuth session callback populates `uuid` - if not, this change will pass `undefined` at runtime
- [ ] Confirm `userUuid` is consumed downstream in the booking service
- [ ] Verify that `PrismaApiKeyRepository.findByHashedKey()` correctly fetches the user's uuid from the database
- [ ] Verify the discriminated union type in `ApiKeyService.ts` ensures `result.user` is always defined when `result.valid` is true
- [ ] Confirm all API v1 endpoints using `req.userUuid` go through the `verifyApiKey` middleware
- [ ] Verify `UserRepository.findByEmailAndIncludeProfilesAndPassword()` includes `uuid` in the select clause
- [ ] Verify SAML login still works correctly - uuid is now optional on User interface so SAML providers don't need to supply it at profile stage
## Updates since last revision
- **Made uuid optional on User, required on Session**: Changed the type strategy so `uuid` is optional on the NextAuth `User` interface but required on `Session.user` via intersection type. This allows SAML providers to not supply uuid at the profile stage while ensuring uuid is always present on the session after the user is resolved from the database.
- **Removed uuid from SAML functions**: Since uuid is now optional on User, the SAML profile and authorize functions no longer need to include it.
---
Link to Devin run: https://app.devin.ai/sessions/97e5603b719a420b9b35041252c9db26
Requested by: hariom@cal.com (@hariombalhara)
* chore(deps): update dependencies and add version constraints
- Update direct dependencies: body-parser, @nestjs/swagger, react-use, trigger.dev
- Add resolutions for consistent dependency versions across the monorepo
- Add packageExtensions to ensure compatible transitive dependency versions
* fix: upgrade rollup resolution from 3.29.5 to 4.22.4
Rollup 3.x is incompatible with vite 5.x which requires rollup ^4.20.0.
The previous resolution caused CI failures due to missing ./parseAst
export
* fix: update axios resolution to 1.13.2
Align resolution with direct dependency in apps/api/v2.
Both versions include the fix, but 1.13.2 is newer and
avoids an unnecessary downgrade
2026-01-01 23:18:53 +00:00
Volnei MunhozGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* chore: upgrade Vitest to 4.0.16 and Vite to 6.4.1
- Update vitest from 2.1.9 to 4.0.16
- Update @vitest/ui from 2.1.9 to 4.0.16
- Update vitest-fetch-mock from 0.3.0 to 0.4.5
- Update vitest-mock-extended from 2.0.2 to 3.1.0
- Update vite from 4.5.14/5.4.21 to 6.4.1 across all packages
- Update @vitejs/plugin-react to 5.1.2
- Update @vitejs/plugin-react-swc to 4.2.2
- Update @vitejs/plugin-basic-ssl to 2.1.0
- Update vite-plugin-dts to 4.5.4
- Rename vitest.config.ts to vitest.config.mts for ESM compatibility
- Add globals: true to vitest config
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: address Vitest 4.0 and Vite 6 breaking changes
- Convert arrow function mockImplementation patterns to regular functions
(Vitest 4.0 breaking change: arrow functions can't be constructor mocks)
- Fix CSS imports with ?inline suffix for Vite 6 compatibility
- Add biome override to disable useArrowFunction rule for test files
- Fix syntax errors in test files introduced by regex replacements
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: fix remaining Vitest 4.0 constructor mock patterns
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: fix more Vitest 4.0 constructor mock patterns and exclude API v2 spec files
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert more arrow function mocks to regular functions for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert more arrow function mocks to regular functions for Vitest 4.0
- Fix CrmService.integration.test.ts jsforce.Connection mock
- Fix RetellSDKClient.test.ts Retell mock
- Fix RetellAIService.test.ts CreditService mocks
- Fix GoogleCalendarSubscriptionAdapter.test.ts CalendarAuth mock
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert Google Calendar and OAuthManager arrow function mocks for Vitest 4.0
- Fix googleapis.ts Calendar, OAuth2Client, and JWT mocks
- Fix utils.ts JWT mock
- Fix OAuthManager.ts defaultMockOAuthManager mock
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add React plugin, jsdom environment, and fix more constructor mocks for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert HostRepository PrismaClient mock to regular function for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add useOrgBranding mock to React component tests for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: update TestFunction type for Vitest 4.0 compatibility
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert listBookingReports constructor mocks to regular functions for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert UserRepository constructor mock to regular function for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert OrganizationPaymentService constructor mock to regular function for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert more constructor mocks to regular functions for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add apps/web path aliases to vitest config
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: fix test issues for Vitest 4.0 compatibility
- Fix Response constructor 204 status code issue in testUtils.ts
- Fix FeaturesRepository mock persistence in handleNotificationWhenNoSlots.test.ts
- Add @vitest-environment node directive to formSubmissionUtils.test.ts
- Fix document.querySelector mock in embed.test.ts
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: clear EventManager spy between tests for Vitest 4.0 compatibility
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: update TeamRepository mock pattern for Vitest 4.0 compatibility
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert RoutingFormResponseRepository mock to regular function for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: convert more constructor mocks to regular functions for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: fix mock reset and spy clear issues for Vitest 4.0
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: fix remaining test failures for Vitest 4.0 upgrade
- Fix booking-validations.test.ts: convert UserRepository mock to regular function
- Fix route.test.ts: update 500 error test to mock ImageResponse instead of fetch
- Fix users-public-view.test.tsx: add missing mocks for getOrgFullOrigin and useRouterQuery
- Add @calcom/web path alias to vitest config
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add vitest-mocks for generated files that don't exist in CI
- Add svg-hashes.json mock for route.test.ts
- Add tailwind.generated.css mock for embed.test.ts
- Update vitest config to use mock files
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: update vitest config aliases for CI compatibility
- Use array format for aliases to ensure proper ordering
- Add @calcom/platform-constants alias to resolve from source
- Add @calcom/embed-react alias to resolve from source
- Ensure svg-hashes.json mock alias is matched before @calcom/web
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: add @calcom/embed-snippet alias for CI compatibility
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* Fix wrong test
* fix: migrate from CLI flags to VITEST_MODE env var for Vitest 4.0
Vitest 4.0 no longer allows custom CLI flags like --packaged-embed-tests-only.
This change migrates to using VITEST_MODE environment variable instead:
- VITEST_MODE=packaged-embed for packaged embed tests
- VITEST_MODE=integration for integration tests
- VITEST_MODE=timezone for timezone-dependent tests
Updated vitest.config.mts to handle mode-based include/exclude patterns.
Updated CI workflows and package scripts to use the new env var approach.
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: return default include pattern instead of undefined in vitest config
The getTestInclude() function was returning undefined for the default case,
but Vitest 4.0 expects an array. This caused 'resolved.include is not iterable'
error in CI.
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: always set INTEGRATION_TEST_MODE for jsdom environment
The getBookingFields.ts file checks for INTEGRATION_TEST_MODE to allow
server-side imports in the jsdom environment. Without this, tests fail
with 'getBookingFields must not be imported on the client side' error.
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
* fix: support legacy CLI flags for backwards compatibility with main workflow
The CI runs workflows from main branch, which uses the old CLI flag approach
(yarn test -- --integrationTestsOnly). This commit adds backwards compatibility
by checking both VITEST_MODE env var and process.argv for the legacy flags.
Co-Authored-By: Volnei Munhoz <volnei.munhoz@gmail.com>
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: ensure proper async handling in ensureDefaultCalendars
Replace forEach(async...) with Promise.allSettled to ensure:
- Caller properly awaits completion
- Errors are captured and logged
- All users are processed even if some fail
Adds unit tests for ensureDefaultCalendars
* fix: use correct Jest assertion pattern for async test
Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>
---------
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- Remove debug console.log statements in calendar and video adapter services
- Clean up verbose request/response logging in OAuth controllers
- Remove leftover debug prefixes
Ensure only necessary data is captured in observability systems
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
* perf: increase E2E test shards from 4 to 6 for faster CI
Increase the number of parallel E2E test shards from 4 to 6 to reduce
overall CI wall-clock time. Each shard runs on a separate 4-vCPU runner
with 4 workers, so adding more shards increases total parallelism.
This should reduce E2E test time from ~3 minutes per shard to ~2 minutes
per shard by distributing tests across more parallel jobs.
Co-Authored-By: anik@cal.com <adhabal2002@gmail.com>
* update
* fix
* update
* readd
* final update
* fix flake
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
- Move managedEventTypeSlug generation inside beforeAll to ensure uniqueness across test runs
- Add deleteAllTeamEventTypes method to EventTypesRepositoryFixture
- Explicitly delete all team event types in afterAll before deleting teams
This fixes flaky tests in organizations-member-team-admin-event-types.e2e-spec.ts
where the managed event type creation was intermittently failing with 400 Bad Request.
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-29 16:12:01 -03:00
Keith WilliamsGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix: add artifact handling for API v2 E2E tests
- Add jest-junit reporter to generate JUnit XML test results
- Update workflow to upload from correct path (apps/api/v2/test-results)
- Add if-no-files-found: ignore and retention-days: 30 for consistency
Co-Authored-By: keith@cal.com <keithwillcode@gmail.com>
* Apply suggestion from @keithwillcode
---------
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit pins all dependency versions in package.json files to exact
versions matching the yarn.lock file, removing ^ and ~ prefixes.
Changes:
- Locked 427 dependencies across 47 package.json files
- Versions now match exactly what is resolved in yarn.lock
- Ensures reproducible builds and prevents unexpected version drift
This change improves build reproducibility by ensuring that the versions
specified in package.json files match exactly what yarn.lock resolves to.
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2025-12-26 11:54:30 -03:00
Anik Dhabal BabuGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
* fix(api): fix user creation with avatarUrl and username
- avatarValidator: accept URLs in addition to base64 images
- organizations-users-service: use email for user creation instead of username
The avatarValidator was incorrectly rejecting valid URLs even though the API documentation shows URL examples and all e2e tests use URLs.
The user creation was failing when username was provided because createNewUsersConnectToOrgIfExists requires a valid email, not username. The username is correctly applied via updateOrganizationUser after creation.
Fixes user creation endpoint POST /v2/organizations/{orgId}/users
* test(api): add tests for avatar validator fixes
Add comprehensive test coverage for avatarValidator changes:
- Unit tests: 18 scenarios covering valid/invalid URLs and base64 images
- E2E tests: user creation with username + avatarUrl (URL and base64)
- Security validation: reject unsafe protocols and malformed data
- Error message verification for validation failures
Addresses testing requirements from code review
* fix(api): enhance avatar validator security per code review
- Reject HTTP URLs, accept only HTTPS for security and browser compatibility
- Reject empty strings and whitespace (use null to reset avatar)
- Update validation message to clarify HTTPS requirement
- Add test coverage for new security restrictions
Addresses security feedback from code review regarding mixed content vulnerabilities and clearer API semantics for avatar reset
* refactor(api): simplify avatarValidator null check
Remove redundant null/undefined check since @IsOptional decorator already skips validation for undefined values. Updated test mock to include @IsOptional to match real DTO usage
---------
Co-authored-by: Keith Williams <keithwillcode@gmail.com>
2025-12-23 15:07:14 +00:00
Hariom BalharaGitHubDevin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
The PATCH endpoint for /v2/teams/:teamId/memberships/:membershipId had a bug
where host records for assignAllTeamMembers event types were not created when
a membership transitioned from accepted=false to accepted=true.
The bug was caused by incorrect operation ordering:
1. Update membership (first update)
2. Get current membership (gets already-updated state)
3. Update membership again (second update)
4. Check if transition happened (condition never fires)
Fixed by reordering to match the org-scoped controller pattern:
1. Get current membership BEFORE any updates
2. Update membership
3. Compare and call updateNewTeamMemberEventTypes if transition occurred
Also added an e2e test to verify host records are created when membership
transitions from accepted=false to accepted=true via PATCH.
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>