Files
Solus/src/auth.js
T

38 lines
1.2 KiB
JavaScript

// 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: 'Nicht autorisiert' }, 401);
}
const provided = extractProvidedToken(c);
if (!provided || !timingSafeStringEqual(expected, provided)) {
return c.json({ error: 'Nicht autorisiert' }, 401);
}
return next();
}