-
Notifications
You must be signed in to change notification settings - Fork 2
Add rate limiting to v5 API routes #16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| # ── Notion ─────────────────────────────────────────────────────────── | ||
| # Internal integration token from https://www.notion.so/my-integrations | ||
| NOTION_API_KEY=ntn_YourTokenHere | ||
|
|
||
| # Notion database IDs (required — share each database with the integration) | ||
| NOTION_DB_TOOLS=YourDatabaseIdHere | ||
| NOTION_DB_CATEGORIES=YourDatabaseIdHere | ||
| NOTION_DB_LOCATIONS=YourDatabaseIdHere | ||
| NOTION_DB_UNITS=YourDatabaseIdHere | ||
| NOTION_DB_RESOURCES=YourDatabaseIdHere | ||
| NOTION_DB_MAINTENANCE_LOGS=YourDatabaseIdHere | ||
| NOTION_DB_FLAGS=YourDatabaseIdHere | ||
|
|
||
| # ── AI APIs ────────────────────────────────────────────────────────── | ||
| # Claude API key for the chat assistant (Vercel AI SDK) | ||
| ANTHROPIC_API_KEY=sk-ant-api03-YourKeyHere | ||
|
|
||
| # ── Admin ──────────────────────────────────────────────────────────── | ||
| # Shared secret guarding POST /api/admin/revalidate | ||
| ADMIN_REVALIDATE_SECRET=YourSecretHere | ||
|
|
||
| # ── Rate limiting (optional) ───────────────────────────────────────── | ||
| # Upstash Redis backs the API rate limiter. When both are set, limits are | ||
| # enforced across all serverless instances. Without them, the limiter falls | ||
| # back to an in-memory store (resets on cold start; fine for basic abuse | ||
| # prevention). | ||
| UPSTASH_REDIS_REST_URL= | ||
| UPSTASH_REDIS_REST_TOKEN= |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| import "server-only"; | ||
|
|
||
| interface RateLimitEntry { | ||
| count: number; | ||
| resetAt: number; | ||
| } | ||
|
|
||
| const store = new Map<string, RateLimitEntry>(); | ||
| const UPSTASH_URL = process.env.UPSTASH_REDIS_REST_URL || ""; | ||
| const UPSTASH_TOKEN = process.env.UPSTASH_REDIS_REST_TOKEN || ""; | ||
| const useUpstash = Boolean(UPSTASH_URL && UPSTASH_TOKEN); | ||
|
|
||
| // Clean up expired entries periodically (every 60s) | ||
| let lastCleanup = Date.now(); | ||
| function cleanup() { | ||
| const now = Date.now(); | ||
| if (now - lastCleanup < 60_000) return; | ||
| lastCleanup = now; | ||
| for (const [key, entry] of store) { | ||
| if (now > entry.resetAt) store.delete(key); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Simple in-memory sliding window rate limiter. | ||
| * Resets on serverless cold start — good enough for abuse prevention. | ||
| */ | ||
| export function rateLimit( | ||
| key: string, | ||
| { limit, windowMs }: { limit: number; windowMs: number } | ||
| ): { allowed: boolean; remaining: number } { | ||
| // Keep sync behavior for callers. If Upstash is configured, callers should use rateLimitAsync. | ||
| if (useUpstash) { | ||
| throw new Error("rateLimitAsync must be used when Upstash Redis is configured"); | ||
| } | ||
| cleanup(); | ||
|
|
||
| const now = Date.now(); | ||
| const entry = store.get(key); | ||
|
|
||
| if (!entry || now > entry.resetAt) { | ||
| store.set(key, { count: 1, resetAt: now + windowMs }); | ||
| return { allowed: true, remaining: limit - 1 }; | ||
| } | ||
|
|
||
| entry.count++; | ||
| const allowed = entry.count <= limit; | ||
| return { allowed, remaining: Math.max(0, limit - entry.count) }; | ||
| } | ||
|
|
||
| export async function rateLimitAsync( | ||
| key: string, | ||
| { limit, windowMs }: { limit: number; windowMs: number } | ||
| ): Promise<{ allowed: boolean; remaining: number }> { | ||
| if (!useUpstash) { | ||
| return rateLimit(key, { limit, windowMs }); | ||
| } | ||
|
|
||
| const redisKey = `rl:${key}`; | ||
| const ttlSec = Math.max(1, Math.ceil(windowMs / 1000)); | ||
| const url = `${UPSTASH_URL}/pipeline`; | ||
| const body = JSON.stringify([ | ||
| ["INCR", redisKey], | ||
| ["EXPIRE", redisKey, ttlSec, "NX"], | ||
| ]); | ||
|
|
||
| const res = await fetch(url, { | ||
| method: "POST", | ||
| headers: { | ||
| Authorization: `Bearer ${UPSTASH_TOKEN}`, | ||
| "Content-Type": "application/json", | ||
| }, | ||
| body, | ||
| cache: "no-store", | ||
| }); | ||
|
|
||
| if (!res.ok) { | ||
| // Fail open to avoid downtime on transient Redis issues. | ||
| return { allowed: true, remaining: limit - 1 }; | ||
| } | ||
|
|
||
| const parsed = (await res.json()) as Array<{ result?: number }>; | ||
| const count = Number(parsed?.[0]?.result || 0); | ||
| const allowed = count <= limit; | ||
| return { allowed, remaining: Math.max(0, limit - count) }; | ||
| } | ||
|
|
||
| /** Extract client IP from request headers (works on Vercel) */ | ||
| export function getClientIp(req: Request): string { | ||
| const forwarded = req.headers.get("x-forwarded-for"); | ||
| if (forwarded) return forwarded.split(",")[0].trim(); | ||
| return req.headers.get("x-real-ip") || "unknown"; | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This new import is not resolvable when the
v5app is installed/built from its own manifest:v5/package.jsondoes not listserver-only, andv5/package-lock.jsonhas nonode_modules/server-onlyentry. Since both API routes now import this module throughrate-limit.ts, a cleanv5build or deployment will fail module resolution before those routes can run; add the dependency to the v5 package/lock or avoid the import here.Useful? React with 👍 / 👎.