Spaces:
Running
Running
File size: 8,118 Bytes
9f29339 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 | "use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var SchedulingController_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchedulingController = void 0;
const common_1 = require("@nestjs/common");
const scheduling_service_1 = require("./scheduling.service");
const config_1 = require("@nestjs/config");
const prisma_service_1 = require("../prisma/prisma.service");
const crypto = __importStar(require("crypto"));
const events_gateway_1 = require("../websocket/events.gateway");
function firstHeader(value) {
if (Array.isArray(value))
return value[0];
return value;
}
function timingSafeEqualStr(provided, expected) {
if (!provided || !expected)
return false;
const a = Buffer.from(provided);
const b = Buffer.from(expected);
if (a.length !== b.length)
return false;
return crypto.timingSafeEqual(a, b);
}
let SchedulingController = SchedulingController_1 = class SchedulingController {
schedulingService;
configService;
prisma;
eventsGateway;
logger = new common_1.Logger(SchedulingController_1.name);
constructor(schedulingService, configService, prisma, eventsGateway) {
this.schedulingService = schedulingService;
this.configService = configService;
this.prisma = prisma;
this.eventsGateway = eventsGateway;
}
async handleWebhook(rawSecretKey, payload) {
const secret = this.configService.get('CALCOM_WEBHOOK_SECRET');
const secretKey = firstHeader(rawSecretKey);
if (!secret) {
if (process.env.NODE_ENV === 'production') {
this.logger.error('CALCOM_WEBHOOK_SECRET not configured — rejecting webhook');
throw new common_1.ForbiddenException('Webhook verification is not configured');
}
this.logger.warn('CALCOM_WEBHOOK_SECRET not configured — webhook signature verification skipped (dev)');
}
else if (!secretKey) {
this.logger.warn('Cal.com webhook rejected: no credentials presented');
throw new common_1.UnauthorizedException('Webhook credentials missing');
}
else if (!timingSafeEqualStr(secretKey, secret)) {
this.logger.warn('Cal.com webhook rejected: invalid x-cal-secret-key');
throw new common_1.UnauthorizedException('Invalid webhook secret');
}
this.logger.log(`Received Cal.com webhook: ${payload.triggerEvent}`);
try {
if (payload.triggerEvent === 'BOOKING_CREATED') {
const { eventTypeId, eventTypeTitle, startTime, endTime, attendees, metadata } = payload.payload;
const guestEmail = attendees[0]?.email;
let workspaceId = null;
if (metadata?.episodeId) {
const booking = await this.schedulingService.createBooking({
episodeId: metadata.episodeId,
startTime,
endTime,
timezone: attendees[0]?.timeZone || 'UTC',
});
const podcast = await this.prisma.podcast.findUnique({
where: { id: booking.episode.podcastId },
select: { workspaceId: true },
});
workspaceId = podcast?.workspaceId ?? null;
}
else if (guestEmail) {
workspaceId = await this.schedulingService.handleCalcomBookingByEmail(guestEmail, startTime, endTime, attendees[0]?.timeZone || 'UTC');
}
if (workspaceId) {
this.eventsGateway.notifyCalComBookingCreated(workspaceId, {
id: String(payload.payload?.uid || payload.payload?.bookingId || ""),
startTime,
endTime,
});
}
}
else if (payload.triggerEvent === 'BOOKING_CANCELLED') {
const uid = String(payload.payload?.uid || payload.payload?.bookingId || "");
if (uid) {
const booking = await this.prisma.booking.findFirst({
where: { OR: [{ calendarEventId: uid }, { meetLink: { contains: uid } }] },
include: {
episode: {
include: {
podcast: { select: { workspaceId: true } },
},
},
},
});
if (booking?.episode?.podcast?.workspaceId) {
this.eventsGateway.notifyCalComBookingCancelled(booking.episode.podcast.workspaceId, booking.id);
}
}
}
}
catch (error) {
this.logger.error(`Error processing webhook: ${error instanceof Error ? error.message : String(error)}`);
}
return { status: 'success' };
}
};
exports.SchedulingController = SchedulingController;
__decorate([
(0, common_1.Post)(),
(0, common_1.HttpCode)(200),
__param(0, (0, common_1.Headers)('x-cal-secret-key')),
__param(1, (0, common_1.Body)()),
__metadata("design:type", Function),
__metadata("design:paramtypes", [Object, Object]),
__metadata("design:returntype", Promise)
], SchedulingController.prototype, "handleWebhook", null);
exports.SchedulingController = SchedulingController = SchedulingController_1 = __decorate([
(0, common_1.Controller)('webhooks/calcom'),
__metadata("design:paramtypes", [scheduling_service_1.SchedulingService,
config_1.ConfigService,
prisma_service_1.PrismaService,
events_gateway_1.EventsGateway])
], SchedulingController);
//# sourceMappingURL=scheduling.controller.js.map |