Files
calendar/packages/lib/checkRateLimitAndThrowError.ts
T
b4a51d3560 feat: auto lock (#18630)
* add delete to redis service

* auto lock + tests

* changes to autolock in api/book call

* remove log clutter

* add detection in api v1

* tpye changes

* throw error and add tests for API

* add response logic on locked + tests

* type response properly i hope?

* type fix

* add tests for counter not existing + redis errors

* remove IP - add sentry to track

* rename symbol

* fix type error

* fix tests

* remove sentry call spy

* fix type on sentry setUser call

---------

Co-authored-by: Alex van Andel <me@alexvanandel.com>
2025-01-18 16:21:12 -03:00

89 lines
2.3 KiB
TypeScript

import prisma from "@calcom/prisma";
import { SMSLockState } from "@calcom/prisma/enums";
import { TRPCError } from "@calcom/trpc/server";
import type { RateLimitHelper } from "./rateLimit";
import { rateLimiter } from "./rateLimit";
export async function checkRateLimitAndThrowError({
rateLimitingType = "core",
identifier,
onRateLimiterResponse,
opts,
}: RateLimitHelper) {
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
const { success, reset } = response;
if (onRateLimiterResponse) onRateLimiterResponse(response);
if (!success) {
const convertToSeconds = (ms: number) => Math.floor(ms / 1000);
const secondsToWait = convertToSeconds(reset - Date.now());
throw new TRPCError({
code: "TOO_MANY_REQUESTS",
message: `Rate limit exceeded. Try again in ${secondsToWait} seconds.`,
});
}
return response;
}
export async function checkSMSRateLimit({
rateLimitingType = "sms",
identifier,
onRateLimiterResponse,
opts,
}: RateLimitHelper) {
const response = await rateLimiter()({ rateLimitingType, identifier, opts });
const { success } = response;
if (onRateLimiterResponse) onRateLimiterResponse(response);
if (!success) {
await changeSMSLockState(
identifier,
rateLimitingType === "sms" ? SMSLockState.LOCKED : SMSLockState.REVIEW_NEEDED
);
}
}
async function changeSMSLockState(identifier: string, status: SMSLockState) {
let userId, teamId;
if (identifier.startsWith("sms:user:")) {
userId = Number(identifier.slice(9));
} else if (identifier.startsWith("sms:team:")) {
teamId = Number(identifier.slice(9));
}
if (userId) {
const user = await prisma.user.findUnique({ where: { id: userId, profiles: { none: {} } } });
if (user?.smsLockReviewedByAdmin) return;
await prisma.user.update({
where: {
id: userId,
profiles: { none: {} },
},
data: {
smsLockState: status,
},
});
} else {
const team = await prisma.team.findUnique({
where: { id: teamId, parentId: null, isOrganization: false },
});
if (team?.smsLockReviewedByAdmin) return;
await prisma.team.update({
where: {
id: teamId,
parentId: null,
isOrganization: false,
},
data: {
smsLockState: status,
},
});
}
}