Files
calendar/packages/features/bot-detection/BotDetectionService.ts
T
sean-brydonandGitHub 7799b191ec feat: botid enabled on api/book/event api route (#24207)
* wip

* WIP

* restore event

* testing without instrument client

* Add conditional for botID init

* Bump BotID version + pass in header

* botID yarn lock changes

* feat: Add feature flag checks + tidy up into service

* rely on env var also

* use eventType repo instead of passing in prisma

* remove slug from audit

* rename botId feature to botid

* add unit tests for bot service
2025-10-06 11:16:13 +01:00

82 lines
2.4 KiB
TypeScript

import { checkBotId } from "botid/server";
import type { IncomingHttpHeaders } from "http";
import type { FeaturesRepository } from "@calcom/features/flags/features.repository";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import type { EventTypeRepository } from "@calcom/lib/server/repository/eventTypeRepository";
interface BotDetectionConfig {
eventTypeId?: number;
headers: IncomingHttpHeaders;
}
const log = logger.getSubLogger({ prefix: ["[BotDetectionService]"] });
export class BotDetectionService {
constructor(
private featuresRepository: FeaturesRepository,
private eventTypeRepository: EventTypeRepository
) {}
private instanceHasBotIdEnabled() {
return process.env.NEXT_PUBLIC_VERCEL_USE_BOTID_IN_BOOKER === "1";
}
async checkBotDetection(config: BotDetectionConfig): Promise<void> {
if (!this.instanceHasBotIdEnabled()) return;
const { eventTypeId, headers } = config;
// If no eventTypeId provided, skip bot detection
if (!eventTypeId) {
return;
}
// Fetch only the teamId from the event type
const eventType = await this.eventTypeRepository.getTeamIdByEventTypeId({
id: eventTypeId,
});
// Only check for team events
if (!eventType?.teamId) {
return;
}
// Check if BotID feature is enabled for this team (also checks global scope - enabling on all teams)
const isBotIDEnabled = await this.featuresRepository.checkIfTeamHasFeature(
eventType.teamId,
"booker-botid"
);
if (!isBotIDEnabled) {
return;
}
// Perform bot detection
const verification = await checkBotId({
advancedOptions: {
headers,
},
});
// Log verification results with detailed information
const verificationDetails = {
isBot: verification.isBot,
isHuman: verification.isHuman,
isVerifiedBot: verification.isVerifiedBot,
verifiedBotName: verification.verifiedBotName,
verifiedBotCategory: verification.verifiedBotCategory,
bypassed: verification.bypassed,
classificationReason: verification.classificationReason,
teamId: eventType.teamId,
eventTypeId,
};
if (verification.isBot) {
log.warn("Bot detected - blocking request", verificationDetails);
throw new HttpError({ statusCode: 403, message: "Access denied" });
}
}
}