Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

enforce stricter rate limits & paid plan checks for any email-related activities

Blue Mouseed4e0b3c443b
diff --git a/backend/apps/cloud/src/common/templates/en/password-change_request.html b/backend/apps/cloud/src/common/templates/en/password-change_request.html
deleted file mode 100644
index cc24b4201..000000000
--- a/backend/apps/cloud/src/common/templates/en/password-change_request.html
+++ /dev/null
@@ -1,7 +0,0 @@
-A request to reset your password for the email associated with swetrix.com has been made. To proceed with changing your password, please confirm by clicking the link below.
-<br/>
-<br/>
-<a href="{{url}}" target="_blank">Confirm password change</a>
-<br/>
-<br/>
-Should you not recognise this request, feel free to disregard this message. No changes will be made to your password unless you activate the link provided and set up a new password.
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index 4450dac70..da31d4ae7 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -92,7 +92,7 @@ export const nFormatter = (num: any, digits = 1) => {
// 'action' is used as a salt to differ rate limiting routes
export const checkRateLimit = async (
- ip: string,
+ key: string,
action: string,
reqAmount: number = RATE_LIMIT_REQUESTS_AMOUNT,
reqTimeout: number = RATE_LIMIT_TIMEOUT,
@@ -101,7 +101,7 @@ export const checkRateLimit = async (
return
}
- const rlHash = getRateLimitHash(ip, action)
+ const rlHash = getRateLimitHash(key, action)
const rlCount = _toNumber(await redis.get(rlHash)) || 0
if (rlCount >= reqAmount) {
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index 23513699c..5e28c0bda 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -4,7 +4,6 @@ export enum LetterTemplate {
PasswordChanged = 'password-change_information',
MailAddressChangeConfirmation = 'mailaddress-change_confirmation',
MailAddressHadChanged = 'mailaddress-change_information',
- PasswordChangeRequest = 'password-change_request',
GDPRDataExport = 'gdpr_data_export',
ProjectReport = 'project-report',
TierWarning = 'tier-warning',
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index 6e9898e95..6488dc05b 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -29,11 +29,6 @@ const metaInfoJson = {
en: () => 'A new e-mail-address has been saved',
},
},
- [LetterTemplate.PasswordChangeRequest]: {
- subject: {
- en: () => 'Changing your password',
- },
- },
[LetterTemplate.PasswordChanged]: {
subject: {
en: () => 'Your password was successfully changed',
diff --git a/backend/apps/cloud/src/organisation/organisation.controller.ts b/backend/apps/cloud/src/organisation/organisation.controller.ts
index 91d24b1ab..f044c0fd8 100644
--- a/backend/apps/cloud/src/organisation/organisation.controller.ts
+++ b/backend/apps/cloud/src/organisation/organisation.controller.ts
@@ -14,6 +14,7 @@ import {
ForbiddenException,
Patch,
ParseIntPipe,
+ Ip,
} from '@nestjs/common'
import { ApiBearerAuth, ApiQuery, ApiResponse } from '@nestjs/swagger'
import { isEmpty as _isEmpty, find as _find, trim as _trim } from 'lodash'
@@ -43,6 +44,7 @@ import { Pagination } from '../common/pagination'
import { ProjectService } from '../project/project.service'
import { Project } from '../project/entity'
import { isDevelopment, PRODUCTION_ORIGIN } from '../common/constants'
+import { checkRateLimit, getIPFromHeaders } from '../common/utils'
const ORGANISATION_INVITE_EXPIRE = 7 * 24 // 7 days in hours
@@ -159,15 +161,20 @@ export class OrganisationController {
async inviteMember(
@Param('orgId') orgId: string,
@Body() inviteDTO: InviteMemberDTO,
- @CurrentUserId() uid: string,
+ @CurrentUserId() userId: string,
@Headers() headers,
+ @Ip() reqIP,
): Promise<Organisation> {
this.logger.log(
- { uid, orgId, inviteDTO },
+ { userId, orgId, inviteDTO },
'POST /organisation/:orgId/invite',
)
- const user = await this.userService.findOne({ where: { id: uid } })
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+ await checkRateLimit(ip, 'org-invite', 5, 1800)
+ await checkRateLimit(userId, 'org-invite', 5, 1800)
+
+ const user = await this.userService.findOne({ where: { id: userId } })
const organisation = await this.organisationService.findOne({
where: { id: orgId },
relations: ['members', 'members.user'],
@@ -179,7 +186,7 @@ export class OrganisationController {
)
}
- await this.organisationService.validateManageAccess(organisation, uid)
+ this.organisationService.validateManageAccess(organisation, userId)
const invitee = await this.userService.findOne({
where: { email: inviteDTO.email },
@@ -196,6 +203,12 @@ export class OrganisationController {
throw new BadRequestException('You cannot invite yourself')
}
+ // if (this.userService.isPaidTier(invitee)) {
+ // throw new BadRequestException(
+ // 'You must be a paid tier subscriber to use this feature.',
+ // )
+ // }
+
const isAlreadyMember = !_isEmpty(
_find(organisation.members, member => member.user?.id === invitee.id),
)
@@ -279,10 +292,7 @@ export class OrganisationController {
)
}
- await this.organisationService.validateManageAccess(
- membership.organisation,
- uid,
- )
+ this.organisationService.validateManageAccess(membership.organisation, uid)
if (membership.user.id === uid) {
throw new BadRequestException('You cannot modify your own role')
@@ -328,10 +338,7 @@ export class OrganisationController {
)
}
- await this.organisationService.validateManageAccess(
- membership.organisation,
- uid,
- )
+ this.organisationService.validateManageAccess(membership.organisation, uid)
if (membership.role === OrganisationRole.owner) {
throw new BadRequestException('Cannot remove organisation owner')
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 0eaa27813..c478fca78 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -22,6 +22,7 @@ import {
UnauthorizedException,
UnprocessableEntityException,
ParseIntPipe,
+ Ip,
} from '@nestjs/common'
import { Response } from 'express'
import {
@@ -79,7 +80,12 @@ import {
MAX_FUNNELS,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
-import { generateRandomId, generateRandomString } from '../common/utils'
+import {
+ checkRateLimit,
+ generateRandomId,
+ generateRandomString,
+ getIPFromHeaders,
+} from '../common/utils'
import {
AddSubscriberParamsDto,
AddSubscriberBodyDto,
@@ -809,7 +815,7 @@ export class ProjectController {
)
}
- await this.organisationService.validateManageAccess(organisation, uid)
+ this.organisationService.validateManageAccess(organisation, uid)
return this.projectService.addProjectToOrganisation(
organisation.id,
@@ -844,7 +850,7 @@ export class ProjectController {
)
}
- await this.organisationService.validateManageAccess(organisation, uid)
+ this.organisationService.validateManageAccess(organisation, uid)
await this.projectService.removeProjectFromOrganisation(
organisation.id,
@@ -1042,10 +1048,16 @@ export class ProjectController {
async share(
@Param('pid') pid: string,
@Body() shareDTO: ShareDTO,
- @CurrentUserId() uid: string,
+ @CurrentUserId() userId: string,
@Headers() headers,
+ @Ip() requestIp: string,
): Promise<Project> {
- this.logger.log({ uid, pid, shareDTO }, 'POST /project/:pid/share')
+ this.logger.log({ userId, pid, shareDTO }, 'POST /project/:pid/share')
+
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'add-subscriber', 10)
+ await checkRateLimit(userId, 'add-subscriber', 10)
if (!isValidPID(pid)) {
throw new BadRequestException(
@@ -1057,14 +1069,20 @@ export class ProjectController {
throw new BadRequestException('The provided ShareDTO is incorrect')
}
- const user = await this.userService.findOne({ where: { id: uid } })
+ const user = await this.userService.findOne({ where: { id: userId } })
const project = await this.projectService.getFullProject(pid)
if (_isEmpty(project)) {
throw new NotFoundException(`Project with ID ${pid} does not exist`)
}
- this.projectService.allowedToManage(project, uid, user.roles)
+ if (this.userService.isPaidTier(user)) {
+ throw new BadRequestException(
+ 'You must be a paid tier subscriber to use this feature.',
+ )
+ }
+
+ this.projectService.allowedToManage(project, userId, user.roles)
const invitee = await this.userService.findOne({
where: { email: shareDTO.email },
@@ -1135,11 +1153,11 @@ export class ProjectController {
await deleteProjectRedis(pid)
return processProjectUser(updatedProject)
- } catch (e) {
+ } catch (reason) {
console.error(
- `[ERROR] Could not share project (pid: ${project.id}, invitee ID: ${invitee.id}): ${e}`,
+ `[ERROR] Could not share project (pid: ${project.id}, invitee ID: ${invitee.id}): ${reason}`,
)
- throw new BadRequestException(e)
+ throw new BadRequestException(reason)
}
}
@@ -1242,9 +1260,15 @@ export class ProjectController {
@Body() body: TransferProjectBodyDto,
@CurrentUserId() userId: string,
@Headers() headers: { origin: string },
+ @Ip() requestIp: string,
) {
this.logger.log({ body }, 'POST /project/transfer')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'transfer-project', 10)
+ await checkRateLimit(userId, 'transfer-project', 10)
+
const project = await this.projectService.getOwnProject(
body.projectId,
userId,
@@ -1384,9 +1408,15 @@ export class ProjectController {
@Body() body: AddSubscriberBodyDto,
@Headers() headers: { origin: string },
@CurrentUserId() userId: string,
+ @Ip() requestIp: string,
) {
this.logger.log({ params, body }, 'POST /project/:projectId/subscribers')
+ const ip = getIPFromHeaders(headers) || requestIp || ''
+
+ await checkRateLimit(ip, 'add-subscriber', 10)
+ await checkRateLimit(userId, 'add-subscriber', 10)
+
const project = await this.projectService.getFullProject(params.projectId)
if (!project) {
@@ -1406,6 +1436,12 @@ export class ProjectController {
throw new BadRequestException('You cannot subscribe to your own project.')
}
+ if (this.userService.isPaidTier(user)) {
+ throw new BadRequestException(
+ 'You must be a paid tier subscriber to use this feature.',
+ )
+ }
+
const subscriber = await this.projectService.getSubscriberByEmail(
params.projectId,
body.email,
diff --git a/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts b/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts
index a50f38475..1acc2e2eb 100644
--- a/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts
+++ b/backend/apps/cloud/src/twoFactorAuth/twoFactorAuth.controller.ts
@@ -63,7 +63,8 @@ export class TwoFactorAuthController {
this.logger.log({ body }, 'POST /2fa/enable')
const ip = getIPFromHeaders(headers) || reqIP || ''
- await checkRateLimit(ip, '2fa-enable', 10, 1800)
+ await checkRateLimit(ip, '2fa-enable', 5, 1800)
+ await checkRateLimit(id, '2fa-enable', 5, 1800)
const user = await this.userService.findOne({ where: { id } })
const { twoFactorAuthenticationCode } = body
@@ -111,7 +112,8 @@ export class TwoFactorAuthController {
this.logger.log({ body }, 'POST /2fa/disable')
const ip = getIPFromHeaders(headers) || reqIP || ''
- await checkRateLimit(ip, '2fa-disable', 10, 1800)
+ await checkRateLimit(ip, '2fa-disable', 5, 1800)
+ await checkRateLimit(id, '2fa-disable', 5, 1800)
const user = await this.userService.findOne({ where: { id } })
const { twoFactorAuthenticationCode } = body
diff --git a/backend/apps/cloud/src/user/user.controller.ts b/backend/apps/cloud/src/user/user.controller.ts
index e1eff739a..3b2a967bf 100644
--- a/backend/apps/cloud/src/user/user.controller.ts
+++ b/backend/apps/cloud/src/user/user.controller.ts
@@ -249,6 +249,7 @@ export class UserController {
const ip = getIPFromHeaders(headers) || reqIP || ''
await checkRateLimit(ip, 'set-paypal-email', 10, 3600)
+ await checkRateLimit(userId, 'set-paypal-email', 10, 3600)
const user = await this.userService.findOne({ where: { id: userId } })
diff --git a/backend/apps/cloud/src/user/user.service.ts b/backend/apps/cloud/src/user/user.service.ts
index ca7f946c4..bfb49909b 100644
--- a/backend/apps/cloud/src/user/user.service.ts
+++ b/backend/apps/cloud/src/user/user.service.ts
@@ -432,6 +432,16 @@ export class UserService {
}
}
+ isPaidTier(user: User) {
+ if (!user) {
+ return false
+ }
+
+ return ![(PlanCode.none, PlanCode.free, PlanCode.trial)].includes(
+ user.planCode,
+ )
+ }
+
async updateSubscription(id: string, planID: number) {
const user = await this.findOne({ where: { id } })
const plan = this.getPlanById(planID)