Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/rate-limiting/guards/tenant-quota.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { Injectable, CanActivate, ExecutionContext, HttpException } from '@nestjs/common';

@Injectable()
export class TenantQuotaGuard implements CanActivate {
private readonly tiers: Record<string, number> = {
FREE: 100,
PRO: 1000,
ENTERPRISE: -1,
};
private counters = new Map<string, { count: number; resetAt: number }>();

canActivate(context: ExecutionContext): boolean {
const req = context.switchToHttp().getRequest();
const tenantId = req.headers['x-tenant-id'] as string;
if (!tenantId) return true;

const tier = (req as any).tenantTier || 'FREE';
const limit = this.tiers[tier] || this.tiers.FREE;
if (limit === -1) return true;

const now = Date.now();
const key = tenantId;
const entry = this.counters.get(key);

if (!entry || now > entry.resetAt) {
this.counters.set(key, { count: 1, resetAt: now + 60000 });
return true;
}

entry.count++;
if (entry.count > limit) {
throw new HttpException('Tenant rate limit exceeded', 429);
}
return true;
}
}
21 changes: 21 additions & 0 deletions src/security/abuse/abuse-score.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Injectable } from '@nestjs/common';

@Injectable()
export class AbuseScoreService {
private scores = new Map<string, { score: number; expiresAt: number }>();

async getCompositeScore(userId: string, ip: string): Promise<number> {
const key = `${userId}:${ip}`;
const entry = this.scores.get(key);
if (!entry || Date.now() > entry.expiresAt) return 0;
return entry.score;
}

addSignal(userId: string, ip: string, weight: number): void {
const key = `${userId}:${ip}`;
const entry = this.scores.get(key);
const now = Date.now();
const newScore = (entry && now <= entry.expiresAt ? entry.score : 0) + weight;
this.scores.set(key, { score: newScore, expiresAt: now + 60000 });
}
}
Loading