All files / server/services rate-limiter.ts

100% Statements 61/61
100% Branches 13/13
100% Functions 17/17
100% Lines 59/59

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 173 174 175 176 177      11x                                       45x   45x     45x 45x   45x 4x     45x 45x           39x 39x   39x 21x 21x 21x     18x 18x 2x 2x           16x 2x 2x     16x 16x 16x 12x 12x 12x     12x                 4x 4x         4x 4x 5x         15x 15x       41x 41x       11x             11x           11x             11x     18x       57x 57x         11x     8x       22x 22x       11x 42x   11x 21x     11x     1x                 3x 3x       11x 3x  
import { Logger } from "@shared/logger";
import { config as serverConfig } from "../config";
 
const logger = new Logger("RateLimiter");
 
interface RateLimitEntry {
  timestamps: number[];
  blockedUntil: number;
  lastActivity: number;
}
 
export interface RateLimitConfig {
  maxRequests: number;
  windowMs: number;
  blockDurationMs: number;
}
 
export type RateLimitResult = { allowed: true } | {
  allowed: false;
  retryAfter: number;
};
 
export class IdentityRateLimiter {
  private readonly identityLimits = new Map<string, RateLimitEntry>();
  private readonly cleanupInterval: NodeJS.Timeout;
  private rejectedTotal = 0;
 
  constructor(
    private readonly name: string,
    private readonly rateConfig: RateLimitConfig,
  ) {
    this.cleanupInterval = setInterval(
      () => this.cleanup(),
      serverConfig.server.simulationRateLimitCleanupIntervalMs,
    );
    this.cleanupInterval.unref?.();
    logger.info(
      `${name} rate limiter initialized: ${rateConfig.maxRequests} request(s) per ${rateConfig.windowMs}ms`,
    );
  }
 
  checkLimit(identity: string): RateLimitResult {
    const now = Date.now();
    let entry = this.identityLimits.get(identity);
 
    if (!entry) {
      entry = { timestamps: [now], blockedUntil: 0, lastActivity: now };
      this.identityLimits.set(identity, entry);
      return { allowed: true };
    }
 
    entry.lastActivity = now;
    if (now < entry.blockedUntil) {
      this.rejectedTotal++;
      return {
        allowed: false,
        retryAfter: Math.max(1, Math.ceil((entry.blockedUntil - now) / 1_000)),
      };
    }
 
    if (entry.blockedUntil > 0) {
      entry.blockedUntil = 0;
      entry.timestamps = [];
    }
 
    const cutoff = now - this.rateConfig.windowMs;
    entry.timestamps = entry.timestamps.filter((timestamp) => timestamp > cutoff);
    if (entry.timestamps.length >= this.rateConfig.maxRequests) {
      entry.blockedUntil = now + this.rateConfig.blockDurationMs;
      this.rejectedTotal++;
      logger.warn(
        `${this.name} rate limit exceeded; blocking identity for ${this.rateConfig.blockDurationMs}ms`,
      );
      return {
        allowed: false,
        retryAfter: Math.max(
          1,
          Math.ceil(this.rateConfig.blockDurationMs / 1_000),
        ),
      };
    }
 
    entry.timestamps.push(now);
    return { allowed: true };
  }
 
  private cleanup(): void {
    const cutoff =
      Date.now() - serverConfig.server.simulationRateLimitInactiveTtlMs;
    for (const [identity, entry] of this.identityLimits) {
      if (entry.lastActivity < cutoff) this.identityLimits.delete(identity);
    }
  }
 
  destroy(): void {
    clearInterval(this.cleanupInterval);
    this.identityLimits.clear();
  }
 
  getStats() {
    const now = Date.now();
    return {
      config: this.rateConfig,
      activeClients: this.identityLimits.size,
      blockedClients: Array.from(this.identityLimits.values()).filter(
        (entry) => entry.blockedUntil > now,
      ).length,
      rejectedTotal: this.rejectedTotal,
    };
  }
}
 
const SIMULATION_DEFAULTS: RateLimitConfig = {
  maxRequests: serverConfig.server.simulationRateLimitMaxRequests,
  windowMs: serverConfig.server.simulationRateLimitWindowMs,
  blockDurationMs: serverConfig.server.simulationRateLimitBlockDurationMs,
};
 
const COMPILE_DEFAULTS: RateLimitConfig = {
  maxRequests: serverConfig.server.compileRateLimitMaxRequests,
  windowMs: serverConfig.server.compileRateLimitWindowMs,
  blockDurationMs: serverConfig.server.compileRateLimitBlockDurationMs,
};
 
export class SimulationRateLimiter extends IdentityRateLimiter {
  private static instance: SimulationRateLimiter | null = null;
 
  private constructor(config: Partial<RateLimitConfig> = {}) {
    super("Simulation start", { ...SIMULATION_DEFAULTS, ...config });
  }
 
  static getInstance(config?: Partial<RateLimitConfig>): SimulationRateLimiter {
    SimulationRateLimiter.instance ??= new SimulationRateLimiter(config);
    return SimulationRateLimiter.instance;
  }
}
 
export class CompileRateLimiter extends IdentityRateLimiter {
  private static instance: CompileRateLimiter | null = null;
 
  private constructor(config: Partial<RateLimitConfig> = {}) {
    super("Compile", { ...COMPILE_DEFAULTS, ...config });
  }
 
  static getInstance(config?: Partial<RateLimitConfig>): CompileRateLimiter {
    CompileRateLimiter.instance ??= new CompileRateLimiter(config);
    return CompileRateLimiter.instance;
  }
}
 
export const getSimulationRateLimiter = (): SimulationRateLimiter =>
  SimulationRateLimiter.getInstance();
 
export const getCompileRateLimiter = (): CompileRateLimiter =>
  CompileRateLimiter.getInstance();
 
export class TutorRateLimiter extends IdentityRateLimiter {
  private static instance: TutorRateLimiter | null = null;
 
  private constructor(config: Partial<RateLimitConfig> = {}) {
    super("Tutor", {
      maxRequests: serverConfig.tutor.rateLimitMaxRequests,
      windowMs: serverConfig.tutor.rateLimitWindowMs,
      blockDurationMs: serverConfig.tutor.rateLimitBlockDurationMs,
      ...config,
    });
  }
 
  static getInstance(config?: Partial<RateLimitConfig>): TutorRateLimiter {
    TutorRateLimiter.instance ??= new TutorRateLimiter(config);
    return TutorRateLimiter.instance;
  }
}
 
export const getTutorRateLimiter = (): TutorRateLimiter =>
  TutorRateLimiter.getInstance();