Files
pulse/lib/pageauth.js
T

140 lines
4.9 KiB
JavaScript
Raw Permalink Normal View History

// Authelia SSO helpers shared by the JSON API middleware (server.js authenticateSSO)
// and the HTML page middleware (authenticatePage).
const crypto = require('crypto');
const net = require('net');
const { renderError } = require('./render');
const ALLOWED_GROUPS = ['admin', 'employee'];
const IDENTITY_HEADERS = ['remote-user', 'remote-name', 'remote-email', 'remote-groups'];
// Parse TRUSTED_PROXIES ("a.b.c.d, a.b.c.0/24, ...") into a BlockList of the
// addresses allowed to send Authelia identity headers. Invalid entries are logged
// and skipped, never widened: "10.0.0.1/" must not become a /0 that trusts everyone.
function parseTrustedProxies(value) {
const list = new net.BlockList();
let count = 0;
for (const raw of String(value || '').split(',')) {
const entry = raw.trim();
if (!entry) continue;
const slash = entry.indexOf('/');
const addr = slash === -1 ? entry : entry.slice(0, slash);
const bits = slash === -1 ? null : entry.slice(slash + 1);
const type = net.isIPv4(addr) ? 'ipv4' : (net.isIPv6(addr) ? 'ipv6' : null);
const maxBits = type === 'ipv4' ? 32 : 128;
if (!type || (bits !== null && !(/^\d{1,3}$/.test(bits) && Number(bits) <= maxBits))) {
console.error(`[Auth] Ignoring invalid TRUSTED_PROXIES entry ${JSON.stringify(entry)}`);
continue;
}
if (bits === null) list.addAddress(addr, type);
else list.addSubnet(addr, Number(bits), type);
count++;
}
return { list, count };
}
let _trusted = null;
// Parsed on first use, after server.js has loaded .env.
function trustedProxies() {
if (!_trusted) _trusted = parseTrustedProxies(process.env.TRUSTED_PROXIES);
return _trusted;
}
// The TCP peer that sent the request. Pulse is reached directly (no local
// reverse proxy), so this is NPM for SSO traffic, and can't be forged by a header.
function requestSource(req) {
let addr = (req.socket && req.socket.remoteAddress) || '';
if (addr.startsWith('::ffff:') && net.isIPv4(addr.slice(7))) addr = addr.slice(7);
return addr;
}
function isTrustedProxy(req, trusted = trustedProxies()) {
const addr = requestSource(req);
const type = net.isIPv4(addr) ? 'ipv4' : (net.isIPv6(addr) ? 'ipv6' : null);
return type !== null && trusted.list.check(addr, type);
}
// The Remote-* identity headers are only real when NPM sent the request, because
// Authelia's forward auth overwrites them; any other LAN host could set them itself.
// Returns null when the request carries no trusted identity. Fails closed: with
// TRUSTED_PROXIES unset, nobody is trusted.
function ssoIdentity(req, trusted = trustedProxies()) {
const h = req.headers;
if (!isTrustedProxy(req, trusted)) {
if (IDENTITY_HEADERS.some(name => h[name])) {
console.warn(`[Auth] Ignored identity headers from untrusted source ${JSON.stringify(requestSource(req))}; ` +
'only TRUSTED_PROXIES may send them');
}
return null;
}
if (!h['remote-user']) return null;
return {
username: h['remote-user'],
name: h['remote-name'],
email: h['remote-email'],
groups: h['remote-groups'] ? h['remote-groups'].split(',').map(g => g.trim()) : []
};
}
// Upsert the SSO user into the `users` table. Extracted verbatim from authenticateSSO.
async function upsertUser(pool, headers) {
const userId = crypto.randomUUID();
await pool.query(
`INSERT INTO users (id, username, display_name, email, groups, last_login)
VALUES (?, ?, ?, ?, ?, NOW())
ON DUPLICATE KEY UPDATE
display_name=VALUES(display_name),
email=VALUES(email),
groups=VALUES(groups),
last_login=NOW()`,
[
userId,
headers['remote-user'],
headers['remote-name'],
headers['remote-email'],
headers['remote-groups']
]
);
}
// Express middleware factory for HTML page routes: same auth rules as the API,
// but failures render a themed HTML page instead of JSON.
function makeAuthenticatePage(pool) {
return async function authenticatePage(req, res, next) {
const identity = ssoIdentity(req);
if (!identity) {
return renderError(req, res, 401, 'Not authenticated',
2026-11-22 01:55:26 -05:00
'Not authenticated. Sign in through Authelia SSO (auth.lotusguild.org).');
}
const { username: remoteUser, name: remoteName, email: remoteEmail, groups } = identity;
const hasAccess = groups.some(g => ALLOWED_GROUPS.includes(g));
if (!hasAccess) {
return renderError(req, res, 403, 'Access denied',
'You must be in the admin or employee group to use this service.');
}
try {
await upsertUser(pool, req.headers);
} catch (error) {
console.error('Error updating user:', error);
}
req.user = {
username: remoteUser,
name: remoteName || remoteUser,
email: remoteEmail || '',
groups: groups,
isAdmin: groups.includes('admin')
};
next();
};
}
module.exports = {
upsertUser, makeAuthenticatePage, ALLOWED_GROUPS,
parseTrustedProxies, trustedProxies, requestSource, isTrustedProxy, ssoIdentity
};