Enhances API infrastructure with Swagger, feature flags, and refactored middleware

Implements @elysiajs/swagger for automated API documentation and introduces a feature flag system to expose service capabilities based on environment variables.

Refactors authentication guards into native Elysia scoped middleware for improved integration and type safety. Updates error handling to support custom status codes and adds instance-specific headers to responses for better observability.

Includes an IP fallback mechanism for bug reports that utilizes internal system info when the direct submitter IP is unavailable.
This commit is contained in:
Flavio Fois
2026-03-17 10:30:42 +01:00
parent 9458d1e8ad
commit 5624019f23
13 changed files with 149 additions and 49 deletions

View File

@@ -1,40 +1,26 @@
import { config } from "../config";
import { Log } from "../logger";
import Elysia from "elysia";
import type { UnauthorizedResponse } from "../types";
// simple middleware functions that enforce API or admin keys
export function apiKeyGuard(ctx: { request?: Request; set: any }) {
const request = ctx.request;
if (!request) return; // nothing to validate at setup time
export const apiKeyGuard2 = new Elysia({ name: "api-key-guard" }).derive(
{ as: "scoped" },
({ headers, status }): UnauthorizedResponse | {} => {
const apiKey = headers["x-api-key"];
if (!apiKey || apiKey !== config.apiKey) {
throw status(401, { success: false as const, message: "Unauthorized API Key" });
}
return {};
},
);
if (request.url.includes("/health")) return;
const key = request.headers.get("x-api-key");
if (!key || key !== config.apiKey) {
const ip =
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
request.headers.get("x-real-ip") ||
"unknown";
Log("AUTH-API-KEYGUARD", `Invalid API key from ip=${ip}`);
ctx.set.status = 401;
return { success: false, message: "Invalid or missing API key" };
}
}
export function adminKeyGuard(ctx: { request?: Request; set: any }) {
const request = ctx.request;
if (!request) return;
if (request.url.includes("/health")) return;
if (request.url.includes("/bug-reports")) return;
const key = request.headers.get("x-admin-key");
if (!key || key !== config.adminKey) {
const ip =
request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
request.headers.get("x-real-ip") ||
"unknown";
Log("AUTH-ADMIN-KEYGUARD", `Invalid admin key from ip=${ip}`);
ctx.set.status = 401;
return { success: false, message: "Invalid or missing admin key" };
}
}
export const adminKeyGuard2 = new Elysia({ name: "admin-key-guard" }).derive(
{ as: "scoped" },
({ headers, status }): UnauthorizedResponse | {} => {
const apiKey = headers["x-admin-key"];
if (!apiKey || apiKey !== config.adminKey) {
throw status(401, { success: false as const, message: "Unauthorized Admin Key" });
}
return {};
},
);