|
| 1 | +const crypto = require("crypto"); |
| 2 | +const db = require("./db"); |
| 3 | + |
| 4 | +// API rate limits per hour |
| 5 | +const API_TIER_LIMITS = { |
| 6 | + anonymous: 60, // No API key, IP-based |
| 7 | + free: 1000, // Free API key |
| 8 | + pro: 10000, // Pro API key |
| 9 | +}; |
| 10 | + |
| 11 | +function ipHash(req) { |
| 12 | + const ip = req.headers["x-forwarded-for"]?.split(",")[0]?.trim() || req.socket.remoteAddress || "unknown"; |
| 13 | + return "api_ip:" + crypto.createHash("sha256").update(ip).digest("hex").slice(0, 16); |
| 14 | +} |
| 15 | + |
| 16 | +function currentHour() { |
| 17 | + const d = new Date(); |
| 18 | + return `${d.toISOString().slice(0, 13)}`; |
| 19 | +} |
| 20 | + |
| 21 | +// Reuse ai_usage table with "api:" prefix for identifiers |
| 22 | +function getApiUsage(identifier, hour) { |
| 23 | + const row = db.prepare("SELECT count FROM ai_usage WHERE identifier = ? AND date = ?").get(identifier, hour); |
| 24 | + return row ? row.count : 0; |
| 25 | +} |
| 26 | + |
| 27 | +function incrementApiUsage(identifier, hour) { |
| 28 | + db.prepare( |
| 29 | + `INSERT INTO ai_usage (identifier, date, count) VALUES (?, ?, 1) |
| 30 | + ON CONFLICT(identifier, date) DO UPDATE SET count = count + 1` |
| 31 | + ).run(identifier, hour); |
| 32 | +} |
| 33 | + |
| 34 | +function lookupApiKey(key) { |
| 35 | + if (!key) return null; |
| 36 | + return db.prepare("SELECT id, tier FROM users WHERE api_key = ?").get(key); |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Express middleware for API rate limiting. |
| 41 | + * Checks API key from Authorization header or query param. |
| 42 | + * Sets X-RateLimit-* headers on response. |
| 43 | + */ |
| 44 | +function apiRateLimit(req, res, next) { |
| 45 | + // Extract API key |
| 46 | + const authHeader = req.headers.authorization; |
| 47 | + const key = authHeader?.startsWith("Bearer ") ? authHeader.slice(7) : req.query.api_key; |
| 48 | + |
| 49 | + let tier = "anonymous"; |
| 50 | + let identifier; |
| 51 | + |
| 52 | + if (key) { |
| 53 | + const user = lookupApiKey(key); |
| 54 | + if (user) { |
| 55 | + tier = user.tier || "free"; |
| 56 | + identifier = "api_user:" + user.id; |
| 57 | + } else { |
| 58 | + return res.status(401).json({ error: "Invalid API key." }); |
| 59 | + } |
| 60 | + } else { |
| 61 | + identifier = ipHash(req); |
| 62 | + } |
| 63 | + |
| 64 | + const limit = API_TIER_LIMITS[tier] ?? API_TIER_LIMITS.anonymous; |
| 65 | + const hour = currentHour(); |
| 66 | + const used = getApiUsage(identifier, hour); |
| 67 | + const remaining = Math.max(0, limit - used); |
| 68 | + |
| 69 | + // Set rate limit headers |
| 70 | + res.setHeader("X-RateLimit-Limit", String(limit)); |
| 71 | + res.setHeader("X-RateLimit-Remaining", String(remaining)); |
| 72 | + res.setHeader("X-RateLimit-Reset", new Date(new Date().setMinutes(60, 0, 0)).toISOString()); |
| 73 | + |
| 74 | + if (used >= limit) { |
| 75 | + res.setHeader("Retry-After", "3600"); |
| 76 | + return res.status(429).json({ |
| 77 | + error: "API rate limit exceeded.", |
| 78 | + limit, |
| 79 | + used, |
| 80 | + tier, |
| 81 | + retryAfter: 3600, |
| 82 | + }); |
| 83 | + } |
| 84 | + |
| 85 | + incrementApiUsage(identifier, hour); |
| 86 | + return next(); |
| 87 | +} |
| 88 | + |
| 89 | +module.exports = { apiRateLimit, API_TIER_LIMITS }; |
0 commit comments