Forráskód Böngészése

feat: AUTH_REQUIRED env var

Sv443 2 hónapja
szülő
commit
95ea2a0e01
3 módosított fájl, 20 hozzáadás és 2 törlés
  1. 3 0
      .env.template
  2. 2 2
      eslint.config.mjs
  3. 15 0
      src/server.ts

+ 3 - 0
.env.template

@@ -16,3 +16,6 @@ GENIUS_ACCESS_TOKEN=
 
 # Comma-separated list of HTTP bearer tokens that are excluded from rate limiting (on geniURL's side)
 AUTH_TOKENS=
+
+# Whether an auth token is required to be able to interact with the API
+AUTH_REQUIRED=false

+ 2 - 2
eslint.config.mjs

@@ -2,7 +2,7 @@ import path from "node:path";
 import { fileURLToPath } from "node:url";
 import typescriptEslint from "@typescript-eslint/eslint-plugin";
 import globals from "globals";
-import tsParser from "@typescript-eslint/parser";
+import parser from "@typescript-eslint/parser";
 import js from "@eslint/js";
 import { FlatCompat } from "@eslint/eslintrc";
 
@@ -43,7 +43,7 @@ const config = [
         GM: "readonly",
         unsafeWindow: "writable",
       },
-      parser: tsParser,
+      parser,
       ecmaVersion: "latest",
       sourceType: "module",
     },

+ 15 - 0
src/server.ts

@@ -40,6 +40,7 @@ const rateLimiter = new RateLimiterMemory(rateLimitOptions);
 
 const toks = getEnvVar("AUTH_TOKENS", "stringArray");
 const authTokens = new Set<string>(Array.isArray(toks) ? toks : []);
+const authRequired = envVarEquals("AUTH_REQUIRED", true, false);
 
 export async function init() {
   const port = getEnvVar("HTTP_PORT", "number"),
@@ -59,6 +60,20 @@ export async function init() {
   // preflight requests
   app.options("*", cors());
 
+  // if auth tokens are required, check for them before doing anything else
+  if(authRequired && authTokens.size < 1) {
+    app.use((req, res, next) => {
+      if(!req.headers.authorization || !authTokens.has(req.headers.authorization.trim().replace(/^Bearer\s+/i, "")))
+        return respond(res, 401, {
+          error: true,
+          matches: null,
+          message: "Unauthorized"
+        }, req?.query?.format ? String(req.query.format) : undefined);
+      else
+        return next();
+    });
+  }
+
   // rate limiting
   app.use(async (req, res, next) => {
     const fmt = req?.query?.format ? String(req.query.format) : undefined;