From 37d46840e37ff6fa8a13a55d3a7bcc6510d2e98d Mon Sep 17 00:00:00 2001 From: orfelorfel23 Date: Wed, 28 Oct 2026 02:51:30 +0100 Subject: [PATCH] Auto-Commit: 2026-10-28 02:51:30 --- src/auth.js | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 src/auth.js diff --git a/src/auth.js b/src/auth.js new file mode 100644 index 0000000..4990180 --- /dev/null +++ b/src/auth.js @@ -0,0 +1,37 @@ +// Admin authentication guard for Solus. +// Protects /api/admin/* routes with a shared secret token. +// The token is read from ADMIN_TOKEN env (or the request, for convenience). +import { timingSafeEqual } from 'node:crypto'; + +function timingSafeStringEqual(a, b) { + if (typeof a !== 'string' || typeof b !== 'string') return false; + const ab = Buffer.from(a, 'utf8'); + const bb = Buffer.from(b, 'utf8'); + if (ab.length !== bb.length) { + // Compare against self to keep constant length, still returns false. + timingSafeEqual(ab, ab); + return false; + } + return timingSafeEqual(ab, bb); +} + +function extractProvidedToken(c) { + const header = c.req.header('x-admin-token'); + if (header && header.trim()) return header.trim(); + const auth = c.req.header('authorization') || ''; + const m = auth.match(/^Bearer\s+(.+)$/i); + if (m && m[1].trim()) return m[1].trim(); + return ''; +} + +export function adminGuard(c, next) { + const expected = process.env.ADMIN_TOKEN || ''; + if (!expected) { + return c.json({ error: 'Admin-Route nicht verfügbar (ADMIN_TOKEN fehlt im Server)' }, 403); + } + const provided = extractProvidedToken(c); + if (!provided || !timingSafeStringEqual(expected, provided)) { + return c.json({ error: 'Nicht autorisiert' }, 401); + } + return next(); +}