File size: 1,808 Bytes
9d4a3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createHash } from "node:crypto";
import { ApiError } from "./api";

type Bucket = {
  count: number;
  resetAt: number;
};

type Store = Map<string, Bucket>;

const globalForRateLimit = globalThis as unknown as { linkedinRateLimits?: Store };
const maxBuckets = 5000;

function store() {
  if (!globalForRateLimit.linkedinRateLimits) globalForRateLimit.linkedinRateLimits = new Map();
  return globalForRateLimit.linkedinRateLimits;
}

function hashIdentifier(value: string) {
  return createHash("sha256").update(value).digest("hex");
}

function clientIdentifier(request: Request) {
  const forwardedFor = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
  return forwardedFor
    ?? request.headers.get("cf-connecting-ip")
    ?? request.headers.get("x-real-ip")
    ?? "local";
}

function pruneExpiredBuckets(values: Store, now: number) {
  if (values.size <= maxBuckets) return;
  for (const [key, bucket] of values) {
    if (bucket.resetAt <= now) values.delete(key);
  }
}

export function enforceRateLimit({ scope, identifier, limit, windowMs }: { scope: string, identifier: string, limit: number, windowMs: number }) {
  const now = Date.now();
  const values = store();
  pruneExpiredBuckets(values, now);

  const key = `${scope}:${hashIdentifier(identifier)}`;
  const existing = values.get(key);
  const bucket = existing && existing.resetAt > now ? existing : { count: 0, resetAt: now + windowMs };

  if (bucket.count >= limit) {
    throw new ApiError(429, "Too many attempts. Try again later.", "rate_limited");
  }

  bucket.count += 1;
  values.set(key, bucket);
}

export function enforceRequestRateLimit(request: Request, options: { scope: string, limit: number, windowMs: number }) {
  enforceRateLimit({ ...options, identifier: clientIdentifier(request) });
}