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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * docs: add JSDoc clarifying error handling guarantees for webhook trigger Co-Authored-By: [email protected] <[email protected]> * 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: [email protected] <[email protected]> * 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 [email protected] Co-Authored-By: [email protected] <[email protected]> * 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: [email protected] <[email protected]> Co-Authored-By: [email protected] <[email protected]> * 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 <[email protected]> Co-authored-by: cal.com <[email protected]>
This commit is contained in:
14 files changed
+452
-36
No files matched your search
@@ -20,6 +20,7 @@ export const WEBHOOK_TRIGGER_EVENTS_GROUPED_BY_APP = {
|
||||
WebhookTriggerEvents.OOO_CREATED,
|
||||
WebhookTriggerEvents.AFTER_HOSTS_CAL_VIDEO_NO_SHOW,
|
||||
WebhookTriggerEvents.AFTER_GUESTS_CAL_VIDEO_NO_SHOW,
|
||||
WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
|
||||
] as const,
|
||||
"routing-forms": [
|
||||
WebhookTriggerEvents.FORM_SUBMITTED,
|
||||
|
||||
@@ -331,6 +331,12 @@ export interface AfterGuestsNoShowDTO extends BaseEventDTO {
|
||||
};
|
||||
}
|
||||
|
||||
export interface DelegationCredentialErrorDTO
|
||||
extends BaseEventDTO,
|
||||
Pick<DelegationCredentialErrorPayloadType, "error" | "credential" | "user"> {
|
||||
triggerEvent: typeof WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR;
|
||||
}
|
||||
|
||||
export type WebhookEventDTO =
|
||||
| BookingCreatedDTO
|
||||
| BookingCancelledDTO
|
||||
@@ -349,7 +355,8 @@ export type WebhookEventDTO =
|
||||
| MeetingEndedDTO
|
||||
| InstantMeetingDTO
|
||||
| AfterHostsNoShowDTO
|
||||
| AfterGuestsNoShowDTO;
|
||||
| AfterGuestsNoShowDTO
|
||||
| DelegationCredentialErrorDTO;
|
||||
|
||||
// Service layer interfaces
|
||||
export interface WebhookTriggerArgs {
|
||||
@@ -482,6 +489,22 @@ export type OOOEntryPayloadType = {
|
||||
};
|
||||
};
|
||||
|
||||
export type DelegationCredentialErrorPayloadType = {
|
||||
error: {
|
||||
type: string;
|
||||
message: string;
|
||||
};
|
||||
credential: {
|
||||
id: number;
|
||||
type: string;
|
||||
appId: string;
|
||||
};
|
||||
user: {
|
||||
id: number;
|
||||
email: string;
|
||||
};
|
||||
};
|
||||
|
||||
export type EventPayloadType = CalendarEvent &
|
||||
TranscriptionGeneratedPayload &
|
||||
EventTypeInfo & {
|
||||
|
||||
@@ -3,6 +3,7 @@ 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";
|
||||
@@ -94,7 +95,11 @@ export type EventPayloadType = CalendarEvent &
|
||||
paymentData?: Payment;
|
||||
};
|
||||
|
||||
export type WebhookPayloadType = EventPayloadType | OOOEntryPayloadType | BookingNoShowUpdatedPayload;
|
||||
export type WebhookPayloadType =
|
||||
| EventPayloadType
|
||||
| OOOEntryPayloadType
|
||||
| BookingNoShowUpdatedPayload
|
||||
| DelegationCredentialErrorPayloadType;
|
||||
|
||||
type WebhookDataType = WebhookPayloadType & { triggerEvent: string; createdAt: string };
|
||||
|
||||
@@ -191,11 +196,17 @@ export function isOOOEntryPayload(data: WebhookPayloadType): data is OOOEntryPay
|
||||
}
|
||||
|
||||
export function isNoShowPayload(data: WebhookPayloadType): data is BookingNoShowUpdatedPayload {
|
||||
return "message" in data;
|
||||
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);
|
||||
return !isNoShowPayload(data) && !isOOOEntryPayload(data) && !isDelegationCredentialErrorPayload(data);
|
||||
}
|
||||
|
||||
const sendPayload = async (
|
||||
@@ -222,7 +233,13 @@ const sendPayload = async (
|
||||
}
|
||||
|
||||
if (body === undefined) {
|
||||
if (template && (isOOOEntryPayload(data) || isEventPayload(data) || isNoShowPayload(data))) {
|
||||
if (
|
||||
template &&
|
||||
(isOOOEntryPayload(data) ||
|
||||
isEventPayload(data) ||
|
||||
isNoShowPayload(data) ||
|
||||
isDelegationCredentialErrorPayload(data))
|
||||
) {
|
||||
body = applyTemplate(template, { ...data, triggerEvent, createdAt }, contentType);
|
||||
} else {
|
||||
body = JSON.stringify({
|
||||
|
||||
@@ -125,6 +125,18 @@ export class WebhookNotificationHandler implements IWebhookNotificationHandler {
|
||||
};
|
||||
}
|
||||
|
||||
case WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR: {
|
||||
return {
|
||||
triggerEvent: dto.triggerEvent,
|
||||
createdAt: dto.createdAt,
|
||||
payload: {
|
||||
error: dto.error,
|
||||
credential: dto.credential,
|
||||
user: dto.user,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default: {
|
||||
// TypeScript exhaustiveness check - this should never happen if all cases are covered
|
||||
const _exhaustiveCheck: never = dto;
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { DelegationCredentialErrorPayloadType } from "@calcom/features/webhooks/lib/dto/types";
|
||||
import type { CalendarAppDelegationCredentialError } from "@calcom/lib/CalendarAppError";
|
||||
import logger from "@calcom/lib/logger";
|
||||
import { WebhookTriggerEvents } from "@calcom/prisma/enums";
|
||||
|
||||
import { WebhookRepository } from "./repository/WebhookRepository";
|
||||
import sendPayload from "./sendPayload";
|
||||
|
||||
const log = logger.getSubLogger({ prefix: ["triggerDelegationCredentialErrorWebhook"] });
|
||||
|
||||
/**
|
||||
* Triggers delegation credential error webhooks for organization webhooks subscribed to DELEGATION_CREDENTIAL_ERROR
|
||||
*/
|
||||
export async function triggerDelegationCredentialErrorWebhook(params: {
|
||||
error: CalendarAppDelegationCredentialError;
|
||||
credential: DelegationCredentialErrorPayloadType["credential"];
|
||||
user: DelegationCredentialErrorPayloadType["user"];
|
||||
orgId?: number | null;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
const { error, credential, user, orgId } = params;
|
||||
|
||||
if (!orgId) {
|
||||
log.debug("Skipping webhook emission - no organization context");
|
||||
return;
|
||||
}
|
||||
|
||||
const webhookRepository = WebhookRepository.getInstance();
|
||||
const webhooks = await webhookRepository.getSubscribers({
|
||||
teamId: orgId,
|
||||
triggerEvent: WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
|
||||
});
|
||||
|
||||
if (webhooks.length === 0) {
|
||||
log.debug("No webhooks subscribed to DELEGATION_CREDENTIAL_ERROR for organization", { orgId });
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
error: {
|
||||
type: error.constructor.name,
|
||||
message: error.message,
|
||||
},
|
||||
credential: {
|
||||
id: credential.id,
|
||||
type: credential.type,
|
||||
appId: credential.appId || "unknown",
|
||||
},
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
} satisfies DelegationCredentialErrorPayloadType;
|
||||
|
||||
const webhookPromises = webhooks.map((webhook) =>
|
||||
sendPayload(
|
||||
webhook.secret,
|
||||
WebhookTriggerEvents.DELEGATION_CREDENTIAL_ERROR,
|
||||
new Date().toISOString(),
|
||||
webhook,
|
||||
payload
|
||||
).catch((err) => {
|
||||
log.error("Failed to send delegation credential error webhook", {
|
||||
webhookId: webhook.id,
|
||||
error: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
})
|
||||
);
|
||||
|
||||
await Promise.allSettled(webhookPromises);
|
||||
|
||||
log.info("Delegation credential error webhooks triggered", {
|
||||
webhookCount: webhooks.length,
|
||||
userId: user.id,
|
||||
credentialId: credential.id,
|
||||
errorType: error.constructor.name,
|
||||
});
|
||||
} catch (webhookError) {
|
||||
log.error("Failed to trigger delegation credential error webhook", {
|
||||
error: webhookError instanceof Error ? webhookError.message : String(webhookError),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user