Cursor prompt

Implement Redis Rate Limiting

Redis sliding window rate limiting middleware with per-user and per-IP tiers, proper headers, and graceful degradation.

Implement Redis-backed rate limiting for {{project_name}}.

## Public limit: {{public_limit}} requests per {{public_window}}
## Auth limit: {{auth_limit}} requests per {{auth_window}}

### Algorithm: Sliding Window with Redis Sorted Sets
```typescript
async function checkRateLimit(key: string, limit: number, windowMs: number): Promise<{
  allowed: boolean;
  remaining: number;
  resetAt: number;
}> {
  const now = Date.now();
  const windowStart = now - windowMs;
  // Remove expired entries
  await redis.zremrangebyscore(key, 0, windowStart);
  // Count current window
  const count = await redis.zcard(key);
  if (count >= limit) {
    const oldest = await redis.zrange(key, 0, 0, 'WITHSCORES');
    return { allowed: false, remaining: 0, resetAt: Number(oldest[1]) + windowMs };
  }
  // Record this request
  await redis.zadd(key, now, `${now}-${Math.random()}`);
  await redis.pexpire(key, windowMs);
  return { allowed: true, remaining: limit - count - 1, resetAt: now + windowMs };
}
```

### Middleware
- Identifier: authenticated userId OR IP (validate X-Forwarded-For — first trusted proxy only)
- Set response headers: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset
- Return 429 with Retry-After header when blocked
- On Redis error: fail open (log error, allow request) — never block traffic due to Redis outage
- Trusted IP bypass: read from RATE_LIMIT_BYPASS_IPS environment variable

### Route-Level Override
```typescript
app.post('/api/auth/login', rateLimit({ limit: 5, window: '15m', key: 'login' }), handler)
```

### Output
Redis client singleton, sliding window implementation, configurable middleware, tests.

Fill in: {{project_name}}, {{public_limit}}, {{public_window}}, {{auth_limit}}, {{auth_window}}. In Loopy you fill these in a form and copy the finished prompt in one click.