( request: NextRequest, endpoint: V1Endpoint = 'logs' )
| 51 | } |
| 52 | |
| 53 | export async function checkRateLimit( |
| 54 | request: NextRequest, |
| 55 | endpoint: V1Endpoint = 'logs' |
| 56 | ): Promise<RateLimitResult> { |
| 57 | try { |
| 58 | const auth = await authenticateV1Request(request) |
| 59 | if (!auth.authenticated) { |
| 60 | return { |
| 61 | allowed: false, |
| 62 | remaining: 0, |
| 63 | limit: 10, |
| 64 | resetAt: new Date(), |
| 65 | error: auth.error, |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | const userId = auth.userId! |
| 70 | const subscription = await getHighestPrioritySubscription(userId) |
| 71 | |
| 72 | const result = await rateLimiter.checkRateLimitWithSubscription( |
| 73 | userId, |
| 74 | subscription, |
| 75 | 'api-endpoint', |
| 76 | false |
| 77 | ) |
| 78 | |
| 79 | if (!result.allowed) { |
| 80 | logger.warn(`Rate limit exceeded for user ${userId}`, { |
| 81 | endpoint, |
| 82 | remaining: result.remaining, |
| 83 | resetAt: result.resetAt, |
| 84 | }) |
| 85 | } |
| 86 | |
| 87 | const plan = (subscription?.plan || 'free') as SubscriptionPlan |
| 88 | const config = getRateLimit(plan, 'api-endpoint') |
| 89 | |
| 90 | return { |
| 91 | allowed: result.allowed, |
| 92 | remaining: result.remaining, |
| 93 | resetAt: result.resetAt, |
| 94 | limit: config.refillRate, |
| 95 | retryAfterMs: result.retryAfterMs, |
| 96 | userId, |
| 97 | workspaceId: auth.workspaceId, |
| 98 | keyType: auth.keyType, |
| 99 | } |
| 100 | } catch (error) { |
| 101 | logger.error('Rate limit check error', { error }) |
| 102 | return { |
| 103 | allowed: false, |
| 104 | remaining: 0, |
| 105 | limit: 10, |
| 106 | resetAt: new Date(Date.now() + 60000), |
| 107 | error: 'Rate limit check failed', |
| 108 | } |
| 109 | } |
| 110 | } |
no test coverage detected