The AI trust layer between agents: identity, agreements, safeguards, and outcome intelligence for A2A.

Viewing files at commit 4e1e50d12753Commit detailsView latest

apps/api/src/security.ts 18 lines · 725 B · typescript
1
export class FixedWindowRateLimiter {
2
  private readonly buckets = new Map<string, { startedAt: number; count: number }>();
3
4
  consume(key: string, limit: number, windowMs: number, now = Date.now()) {
5
    const current = this.buckets.get(key);
6
    if (!current || now - current.startedAt >= windowMs) {
7
      this.buckets.set(key, { startedAt: now, count: 1 });
8
      return { allowed: true, remaining: Math.max(0, limit - 1), retryAfterSeconds: 0 };
9
    }
10
    current.count += 1;
11
    const retryAfterSeconds = Math.max(1, Math.ceil((windowMs - (now - current.startedAt)) / 1000));
12
    return {
13
      allowed: current.count <= limit,
14
      remaining: Math.max(0, limit - current.count),
15
      retryAfterSeconds,
16
    };
17
  }
18
}