Files
calendar/packages/features/webhooks/lib/sendPayload.ts
T
Rajiv SahalGitHubmorgan@cal.com <morgan@cal.com>rajiv@cal.com <sahalrajiv6900@gmail.com>Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>Morgancal.com
e6d44ce620 feat: Add delegation credential error webhook trigger (#24871)
* feat: add delegation credential error webhook trigger

- Add DELEGATION_CREDENTIAL_ERROR to WebhookTriggerEvents enum
- Create DelegationCredentialErrorDTO type for webhook payload
- Implement DelegationCredentialErrorWebhookService
- Add translation for delegation_credential_error
- Enable webhook for API v2 organization webhooks

This webhook will send delegation credential error data to configured URLs when errors occur during calendar authentication with delegation credentials.

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

* fix: add delegation credential error payload type and type guards

- Add DelegationCredentialErrorPayloadType to sendPayload.ts
- Update WebhookPayloadType union to include new payload type
- Add isDelegationCredentialErrorPayload type guard function
- Update isEventPayload to exclude delegation credential errors
- Update template application logic to handle new payload type
- Add corresponding payload type to dto/types.ts for consistency

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

* feat: add delegation credential error handling to WebhookNotificationHandler

- Add DELEGATION_CREDENTIAL_ERROR case to createPayload switch
- Return payload with error, credential, and user data
- Ensures exhaustive type checking passes for new trigger

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

* feat: restrict DELEGATION_CREDENTIAL_ERROR to organization webhooks only

- Add validation in UserWebhooksService to reject DELEGATION_CREDENTIAL_ERROR
- Add validation in EventTypeWebhooksService to reject DELEGATION_CREDENTIAL_ERROR
- Ensures trigger is only available for API v2 organization webhooks as requested

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

* feat: wire up delegation credential error webhook emission in calendar services

- Add webhook emission calls in CalendarAuth.ts for Google Calendar delegation errors
- Add webhook emission calls in Office365 CalendarService.ts for Azure AD delegation errors
- Implement actual webhook emission using WebhookRepository pattern
- Fix pre-existing lint warnings in Office365 CalendarService.ts (unused catch variables, unsafe optional chaining)

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

* test: add e2e tests for DELEGATION_CREDENTIAL_ERROR webhook trigger

- Add comprehensive e2e tests for creating, retrieving, updating, and deleting webhooks with DELEGATION_CREDENTIAL_ERROR trigger
- Test combining DELEGATION_CREDENTIAL_ERROR with other triggers
- Fix import in triggerDelegationCredentialErrorWebhook.ts to use default import for sendPayload
- Tests follow existing patterns in organizations-webhooks.e2e-spec.ts

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

* refactor: remove name field from webhook payload and delete unused service

- Remove name field from triggerDelegationCredentialErrorWebhook function signature and payload
- Update all call sites in GoogleCalendar and Office365 calendar services
- Update DelegationCredentialErrorDTO and DelegationCredentialErrorPayloadType to remove name field
- Delete unused DelegationCredentialErrorWebhookService.ts (dead code - not used anywhere)
- The helper function approach is more appropriate for app-store integrations without DI

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

* refactor: make fire-and-forget intent explicit for webhook emission

- Add void cast to all triggerDelegationCredentialErrorWebhook calls
- Remove redundant .catch() handlers (helper already handles errors internally)
- This makes it clear that webhook emission is non-blocking by design
- Avoids delaying error propagation while webhook HTTP requests complete

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

* feat: await webhook emission and add HTTP timeout for guaranteed delivery

- Change all triggerDelegationCredentialErrorWebhook calls from void to await
- Add 10-second timeout to webhook HTTP requests using AbortController
- Remove name field from DelegationCredentialErrorPayloadType to match payload
- Ensures webhooks are sent before error is thrown (per user requirement)
- Prevents indefinite hangs on unresponsive webhook endpoints

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

* fix: make getAuthUrl async and await all call sites

- Make getAuthUrl async to support awaiting webhook emission
- Add await to all 3 getAuthUrl call sites (constructor, getAzureUserId, testDelegationCredentialSetup)
- Remove leftover name field from getAzureUserId webhook call
- Fixes TS1308 error about await in non-async function

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

* docs: add JSDoc clarifying error handling guarantees for webhook trigger

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

* Revert "docs: add JSDoc clarifying error handling guarantees for webhook trigger"

This reverts commit 3e33090197bfe2f2e3fb890402b32e04c44305e3.

* Revert "fix: make getAuthUrl async and await all call sites"

This reverts commit de28b7337149104412c861fd9b05e76fffc1fed7.

* Revert "feat: await webhook emission and add HTTP timeout for guaranteed delivery"

This reverts commit 9da7241f83a8373b4fadc03ccf34e097c28adf3a.

* Revert "refactor: make fire-and-forget intent explicit for webhook emission"

This reverts commit f4f7fa06b7dfa151bfbea29905b8783261d9f353.

* feat: await webhook emission to match standard pattern

- Updated all webhook call sites to await triggerDelegationCredentialErrorWebhook
- Made getAuthUrl async and updated all 3 call sites to await it
- Removed .catch() wrappers at call sites (error handling is in trigger function)
- Matches standard pattern used in WebhookService.sendPayload with Promise.allSettled
- Ensures webhooks are sent before delegation errors are thrown

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

* fix: address PR feedback - add migration, remove 'as any', remove user.name

- Add Prisma migration for DELEGATION_CREDENTIAL_ERROR enum
- Replace 'as any' type casting with safe type-narrowing helper in CalendarAuth.ts
- Remove user.name field from DelegationCredentialErrorPayloadType (email is sufficient)
- Ensure all type definitions are consistent across sendPayload.ts and dto/types.ts

Addresses feedback from alishaz-polymath and morgan@cal.com

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

* chore: cleanup type in CalendarAuth

* fix: missing DELEGATION_CREDENTIAL_ERROR in WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP constant

* fix: review

* fit: import webhook dto

* fit: type error

* feat: add delegation credential error webhook handling to Office365 video adapter

- Emit webhook before throwing delegation credential errors in Office365 video
- Added webhook emission in 4 locations:
  1. Missing clientId/Secret in fetchNewTokenObject
  2. Missing tenantId in getAuthUrl
  3. Missing clientId/Secret in getAzureUserId
  4. User doesn't exist in Azure AD
- Made getAuthUrl async to support webhook emission
- Follows same pattern as GoogleCalendar and Office365Calendar implementations

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

* fixup! Merge branch 'devin/delegation-credential-errors-webhook-1762171203' of https://git-manager.devin.ai/proxy/github.com/calcom/cal.com into devin/delegation-credential-errors-webhook-1762171203

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Morgan <33722304+ThyMinimalDev@users.noreply.github.com>
Co-authored-by: cal.com <morgan@cal.com>
2025-11-11 16:02:06 +02:00

322 lines
8.7 KiB
TypeScript

import { createHmac } from "crypto";
import { compile } from "handlebars";
import type { TGetTranscriptAccessLink } from "@calcom/app-store/dailyvideo/zod";
import { getHumanReadableLocationValue } from "@calcom/app-store/locations";
import { DelegationCredentialErrorPayloadType } from "@calcom/features/webhooks/lib/dto/types";
import { getUTCOffsetByTimezone } from "@calcom/lib/dayjs";
import type { Payment, Webhook } from "@calcom/prisma/client";
import type { CalendarEvent, Person } from "@calcom/types/Calendar";
type ContentType = "application/json" | "application/x-www-form-urlencoded";
export type EventTypeInfo = {
eventTitle?: string | null;
eventDescription?: string | null;
requiresConfirmation?: boolean | null;
price?: number | null;
currency?: string | null;
length?: number | null;
};
export type UTCOffset = {
utcOffset?: number | null;
};
export type WithUTCOffsetType<T> = T & {
user?: Person & UTCOffset;
} & {
organizer?: Person & UTCOffset;
} & {
attendees?: (Person & UTCOffset)[];
};
export type BookingNoShowUpdatedPayload = {
message: string;
bookingUid: string;
bookingId?: number;
attendees: { email: string; noShow: boolean }[];
};
export type TranscriptionGeneratedPayload = {
downloadLinks?: {
transcription: TGetTranscriptAccessLink["transcription"];
recording: string;
};
};
export type OOOEntryPayloadType = {
oooEntry: {
id: number;
start: string;
end: string;
createdAt: string;
updatedAt: string;
notes: string | null;
reason: {
emoji?: string;
reason?: string;
};
reasonId: number;
user: {
id: number;
name: string | null;
username: string | null;
timeZone: string;
email: string;
};
toUser: {
id: number;
name?: string | null;
username?: string | null;
timeZone?: string;
email?: string;
} | null;
uuid: string;
};
};
export type EventPayloadType = CalendarEvent &
TranscriptionGeneratedPayload &
EventTypeInfo & {
uid?: string | null;
metadata?: { [key: string]: string | number | boolean | null };
bookingId?: number;
status?: string;
smsReminderNumber?: string;
rescheduleId?: number;
rescheduleUid?: string;
rescheduleStartTime?: string;
rescheduleEndTime?: string;
downloadLink?: string;
paymentId?: number;
rescheduledBy?: string;
cancelledBy?: string;
paymentData?: Payment;
};
export type WebhookPayloadType =
| EventPayloadType
| OOOEntryPayloadType
| BookingNoShowUpdatedPayload
| DelegationCredentialErrorPayloadType;
type WebhookDataType = WebhookPayloadType & { triggerEvent: string; createdAt: string };
function addUTCOffset(data: WebhookPayloadType): WithUTCOffsetType<WebhookPayloadType> {
if (isEventPayload(data)) {
if (data.organizer?.timeZone) {
(data.organizer as Person & UTCOffset).utcOffset = getUTCOffsetByTimezone(
data.organizer.timeZone,
data.startTime
);
}
if (data.attendees?.length) {
(data.attendees as (Person & UTCOffset)[]).forEach((attendee) => {
attendee.utcOffset = getUTCOffsetByTimezone(attendee.timeZone, data.startTime);
});
}
}
return data as WithUTCOffsetType<WebhookPayloadType>;
}
function getZapierPayload(data: WithUTCOffsetType<EventPayloadType & { createdAt: string }>): string {
const attendees = (data.attendees as (Person & UTCOffset)[]).map((attendee) => {
return {
name: attendee.name,
email: attendee.email,
timeZone: attendee.timeZone,
utcOffset: attendee.utcOffset,
};
});
const t = data.organizer.language.translate;
const location = getHumanReadableLocationValue(data.location || "", t);
const body = {
uid: data.uid,
title: data.title,
description: data.description,
customInputs: data.customInputs,
responses: data.responses,
userFieldsResponses: data.userFieldsResponses,
startTime: data.startTime,
endTime: data.endTime,
location: location,
status: data.status,
cancellationReason: data.cancellationReason,
user: {
username: data.organizer.username,
usernameInOrg: data.organizer.usernameInOrg,
name: data.organizer.name,
email: data.organizer.email,
timeZone: data.organizer.timeZone,
utcOffset: data.organizer.utcOffset,
locale: data.organizer.locale,
},
eventType: {
title: data.eventTitle,
description: data.eventDescription,
requiresConfirmation: data.requiresConfirmation,
price: data.price,
currency: data.currency,
length: data.length,
},
attendees: attendees,
createdAt: data.createdAt,
metadata: {
videoCallUrl: data.metadata?.videoCallUrl,
},
};
return JSON.stringify(body);
}
function applyTemplate(template: string, data: WebhookDataType, contentType: ContentType) {
const compiled = compile(template)(data).replace(/&quot;/g, '"');
if (contentType === "application/json") {
return JSON.stringify(jsonParse(compiled));
}
return compiled;
}
export function jsonParse(jsonString: string) {
try {
return JSON.parse(jsonString);
} catch {
// don't do anything.
}
return false;
}
export function isOOOEntryPayload(data: WebhookPayloadType): data is OOOEntryPayloadType {
return "oooEntry" in data;
}
export function isNoShowPayload(data: WebhookPayloadType): data is BookingNoShowUpdatedPayload {
return "message" in data && "bookingUid" in data;
}
export function isDelegationCredentialErrorPayload(
data: WebhookPayloadType
): data is DelegationCredentialErrorPayloadType {
return "error" in data && "credential" in data && "user" in data;
}
export function isEventPayload(data: WebhookPayloadType): data is EventPayloadType {
return !isNoShowPayload(data) && !isOOOEntryPayload(data) && !isDelegationCredentialErrorPayload(data);
}
const sendPayload = async (
secretKey: string | null,
triggerEvent: string,
createdAt: string,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
data: WebhookPayloadType
) => {
const { appId, payloadTemplate: template } = webhook;
const contentType =
!template || jsonParse(template) ? "application/json" : "application/x-www-form-urlencoded";
data = addUTCOffset(data);
let body;
/* Zapier id is hardcoded in the DB, we send the raw data for this case */
if (isEventPayload(data)) {
data.description = data.description || data.additionalNotes;
if (appId === "zapier") {
body = getZapierPayload({ ...data, createdAt });
}
}
if (body === undefined) {
if (
template &&
(isOOOEntryPayload(data) ||
isEventPayload(data) ||
isNoShowPayload(data) ||
isDelegationCredentialErrorPayload(data))
) {
body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
} else {
body = JSON.stringify({
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
}
}
return _sendPayload(secretKey, webhook, body, contentType);
};
export const sendGenericWebhookPayload = async ({
secretKey,
triggerEvent,
createdAt,
webhook,
data,
rootData,
}: {
secretKey: string | null;
triggerEvent: string;
createdAt: string;
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">;
data: Record<string, unknown>;
rootData?: Record<string, unknown>;
}) => {
const body = JSON.stringify({
// Added rootData props first so that using the known(i.e. triggerEvent, createdAt, payload) properties in rootData doesn't override the known properties
...rootData,
triggerEvent: triggerEvent,
createdAt: createdAt,
payload: data,
});
return _sendPayload(secretKey, webhook, body, "application/json");
};
export const createWebhookSignature = (params: { secret?: string | null; body: string }) =>
params.secret
? createHmac("sha256", params.secret).update(`${params.body}`).digest("hex")
: "no-secret-provided";
const _sendPayload = async (
secretKey: string | null,
webhook: Pick<Webhook, "subscriberUrl" | "appId" | "payloadTemplate">,
body: string,
contentType: "application/json" | "application/x-www-form-urlencoded"
) => {
const { subscriberUrl } = webhook;
if (!subscriberUrl || !body) {
throw new Error("Missing required elements to send webhook payload.");
}
const response = await fetch(subscriberUrl, {
method: "POST",
headers: {
"Content-Type": contentType,
"X-Cal-Signature-256": createWebhookSignature({ secret: secretKey, body }),
},
redirect: "manual",
body,
});
const text = await response.text();
return {
ok: response.ok,
status: response.status,
...(text
? {
message: text,
}
: {}),
};
};
export default sendPayload;