From 85a526d1b64fd8a92e730d6dd392015cc1640ff8 Mon Sep 17 00:00:00 2001 From: "Wei S." <5291640+wayneshn@users.noreply.github.com> Date: Thu, 4 Sep 2025 17:32:43 +0300 Subject: [PATCH] User api key: JSON rate limiting message & status code (#87) * feat(auth): Implement API key authentication This commit enables API access with an API key system. This change provides a better experience for programmatic access and third-party integrations. Key changes include: - **API Key Management:** Users can now generate, manage, and revoke persistent API keys through a new "API Keys" section in the settings UI. - **Authentication Middleware:** API requests are now authenticated via an `X-API-KEY` header instead of the previous `Authorization: Bearer` token. - **Backend Implementation:** Adds a new `api_keys` database table, along with corresponding services, controllers, and routes to manage the key lifecycle securely. - **Rate Limiting:** The API rate limiter now uses the API key to identify and track requests. - **Documentation:** The API authentication documentation has been updated to reflect the new method. * Add configurable API rate limiting Two new variables are added to `.env.example`: - `RATE_LIMIT_WINDOW_MS`: The time window in milliseconds for which requests are checked (defaults to 15 minutes). - `RATE_LIMIT_MAX_REQUESTS`: The maximum number of requests allowed from an IP within the window (defaults to 100). The installation documentation has been updated to reflect these new configuration options. * Disable API operation in demo mode * Exclude public API endpoints from rate limiting * JSON rate limiting message & status code --------- Co-authored-by: Wayne <5291640+ringoinca@users.noreply.github.com> --- packages/backend/src/api/middleware/rateLimiter.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/backend/src/api/middleware/rateLimiter.ts b/packages/backend/src/api/middleware/rateLimiter.ts index 4042325..9eb514a 100644 --- a/packages/backend/src/api/middleware/rateLimiter.ts +++ b/packages/backend/src/api/middleware/rateLimiter.ts @@ -6,7 +6,11 @@ const windowInMinutes = Math.ceil(config.api.rateLimit.windowMs / 60000); export const rateLimiter = rateLimit({ windowMs: config.api.rateLimit.windowMs, max: config.api.rateLimit.max, - message: `Too many requests from this IP, please try again after ${windowInMinutes} minutes`, + message: { + status: 429, + message: `Too many requests from this IP, please try again after ${windowInMinutes} minutes` + }, + statusCode: 429, standardHeaders: true, - legacyHeaders: false, + legacyHeaders: false });