Let an installation look different via ENVIRONMENT_NAME and ENVIRONMENT_COLOR

Setting ENVIRONMENT_NAME (and optionally ENVIRONMENT_COLOR, a name or hex
value) gives the sidebar that colour, adds a name badge next to the title and
on the sign-in page, and prefixes the browser tab title, so a dev copy can't
be taken for production. Unset, nothing changes. The colour is validated to a
plain #rrggbb before it reaches the page's styles. A public
GET /api/environment lets the sign-in page use it too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-13 20:59:25 +02:00
1 parent 44cc9d1cf2
commit 7e196be56d
11 files changed
+253 -3

No files matched your search

+8
View File
@@ -1,6 +1,14 @@
# Public URL the app is reachable at (used for OIDC redirect_uri and cookie behavior).
APP_BASE_URL=https://homelab.example.lan
# Optional: make this installation look different, so a dev copy can't be taken for production.
# The sidebar takes the colour, a badge with the name is shown next to the title (and on the sign-in page),
# and the browser tab reads "[Dev] Homelab Manager". Leave both out for the normal look.
# ENVIRONMENT_COLOR is a name (red, orange, amber, green, teal, blue, purple, pink, gray) or a hex value like #b45309.
# A name without a colour gets orange.
# ENVIRONMENT_NAME=Dev
# ENVIRONMENT_COLOR=orange
# Random long string used to sign session cookies. Generate with:
# node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
# Required in production: without it the app refuses to start (the alternative is a value that is
+9
View File
@@ -425,6 +425,15 @@ docker compose up -d
The app listens on `HOST_PORT` (default `3000`); SQLite data persists in
`./data` on the host.
**Telling a dev copy from production:** set `ENVIRONMENT_NAME` (e.g. `Dev`) and
optionally `ENVIRONMENT_COLOR` in that instance's `.env` (or under `environment:`
in its compose file). The sidebar then takes the colour, a badge with the name
sits next to the title and on the sign-in page, and the browser tab reads
`[Dev] Homelab Manager`. The colour is a name (`red`, `orange`, `amber`, `green`,
`teal`, `blue`, `purple`, `pink`, `gray`) or a hex value such as `#b45309`; a
name alone gets orange. Leave both unset on production and nothing changes.
Restart the container after changing them.
### arm64 (Raspberry Pi, Apple silicon, ARM servers)
Two compose files, one to build the image and one to run the published one:
+4
View File
@@ -74,6 +74,10 @@ export function createApp() {
app.get("/health", (_req, res) => res.json({ ok: true }));
// What this installation calls itself and how it should look (a dev copy in a different colour), asked for before sign-in so the
// login page can show it too. Just a label and a colour.
app.get("/api/environment", (_req, res) => res.json({ environment: env.environment }));
// Publicly readable so `curl .../agent/linux/install.sh | bash` works from a
// freshly provisioned server with no prior session. Contains no secrets.
if (existsSync(agentDir)) {
+47
View File
@@ -1,3 +1,48 @@
/** Colours that can be asked for by name; all dark enough to carry white text. Anything else must be a hex colour. */
export const ENVIRONMENT_COLORS: Record<string, string> = {
red: "#b91c1c",
orange: "#c2410c",
amber: "#b45309",
green: "#15803d",
teal: "#0f766e",
blue: "#1d4ed8",
purple: "#7e22ce",
pink: "#be185d",
gray: "#475569",
grey: "#475569",
};
const DEFAULT_ENVIRONMENT_COLOR = ENVIRONMENT_COLORS.orange;
export interface EnvironmentLook {
/** Shown as a badge and in the browser tab; may be empty when only a colour was set. */
name: string;
/** A #rrggbb colour. */
color: string;
}
/**
* How this installation says what it is — so a dev copy can't be mistaken for production. Both values come from the environment
* (ENVIRONMENT_NAME, ENVIRONMENT_COLOR). Neither set means a normal look; a name alone gets a default colour. The colour is only
* ever a validated #rrggbb value, because it is placed into the page's styles.
*/
export function parseEnvironment(nameRaw: string | undefined, colorRaw: string | undefined): { look: EnvironmentLook | null; warning?: string } {
const name = (nameRaw ?? "").replace(/\p{Cc}/gu, "").trim().slice(0, 24);
const wanted = (colorRaw ?? "").trim().toLowerCase();
let color: string | null = null;
let warning: string | undefined;
if (wanted) {
if (ENVIRONMENT_COLORS[wanted]) color = ENVIRONMENT_COLORS[wanted];
else if (/^#[0-9a-f]{6}$/.test(wanted)) color = wanted;
else if (/^#[0-9a-f]{3}$/.test(wanted)) color = `#${wanted[1]}${wanted[1]}${wanted[2]}${wanted[2]}${wanted[3]}${wanted[3]}`;
else warning = `ENVIRONMENT_COLOR "${colorRaw}" isn't a colour name (${Object.keys(ENVIRONMENT_COLORS).join(", ")}) or a hex value like #b45309 — using the default.`;
}
if (!name && !color) return { look: null, warning };
return { look: { name, color: color ?? DEFAULT_ENVIRONMENT_COLOR }, warning };
}
const environmentLook = parseEnvironment(process.env.ENVIRONMENT_NAME, process.env.ENVIRONMENT_COLOR);
export const env = {
port: Number(process.env.PORT ?? 3000),
nodeEnv: process.env.NODE_ENV ?? "development",
@@ -11,6 +56,8 @@ export const env = {
clientId: process.env.AUTHENTIK_CLIENT_ID ?? "",
clientSecret: process.env.AUTHENTIK_CLIENT_SECRET ?? "",
},
environment: environmentLook.look,
environmentWarning: environmentLook.warning,
get authEnabled() {
return Boolean(this.authentik.issuerUrl && this.authentik.clientId && this.authentik.clientSecret);
},
+2
View File
@@ -25,6 +25,8 @@ import { initKumaMaintenanceScheduler } from "./services/kumaMaintenanceSchedule
}
warnIfAuthNotConfigured();
if (env.environmentWarning) console.warn(env.environmentWarning);
if (env.environment) console.log(`Environment: ${env.environment.name || "(unnamed)"} (${env.environment.color})`);
await runMigrations();
{
const converted = await encryptStoredSettingsSecrets();
+85
View File
@@ -0,0 +1,85 @@
/**
* Making a dev installation look different from production (ENVIRONMENT_NAME / ENVIRONMENT_COLOR).
*
* Run with: npm test --workspace server
*/
import { test, describe, before, after } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AddressInfo } from "node:net";
import type { Server } from "node:http";
const dir = mkdtempSync(join(tmpdir(), "hm-environment-"));
process.env.DATABASE_PATH = join(dir, "test.sqlite");
process.env.SESSION_DIR = join(dir, "sessions");
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
process.env.ENVIRONMENT_NAME = "Dev";
process.env.ENVIRONMENT_COLOR = "teal";
const { parseEnvironment } = await import("../src/env.js");
const { createApp } = await import("../src/app.js");
describe("parseEnvironment", () => {
test("nothing set is a normal installation", () => {
assert.deepEqual(parseEnvironment(undefined, undefined), { look: null, warning: undefined });
assert.deepEqual(parseEnvironment(" ", ""), { look: null, warning: undefined });
});
test("a name alone gets the default colour", () => {
const { look } = parseEnvironment("Dev", undefined);
assert.equal(look?.name, "Dev");
assert.match(look?.color ?? "", /^#[0-9a-f]{6}$/);
});
test("colours by name or as hex, in any case, short hex expanded", () => {
assert.equal(parseEnvironment("x", "Blue").look?.color, "#1d4ed8");
assert.equal(parseEnvironment("x", "#B45309").look?.color, "#b45309");
assert.equal(parseEnvironment("x", "#0af").look?.color, "#00aaff");
});
test("a colour alone is accepted, with no name", () => {
assert.deepEqual(parseEnvironment(undefined, "green").look, { name: "", color: "#15803d" });
});
test("anything that is not a plain colour is refused, never passed on into the page's styles", () => {
for (const bad of ["red; background:url(//evil)", "url(x)", "#12345", "rgb(1,2,3)", "</style><script>", "#zzzzzz"]) {
const { look, warning } = parseEnvironment("Dev", bad);
assert.match(look?.color ?? "", /^#[0-9a-f]{6}$/, `${bad} falls back to a safe colour`);
assert.ok(warning, `${bad} is reported`);
}
});
test("the name is cleaned of control characters and capped in length", () => {
assert.equal(parseEnvironment("De\u0000v\n", undefined).look?.name, "Dev");
assert.equal(parseEnvironment("x".repeat(100), undefined).look?.name.length, 24);
});
});
describe("GET /api/environment", () => {
let server: Server;
let base = "";
before(async () => {
server = await new Promise<Server>((resolve) => {
const s = createApp().listen(0, "127.0.0.1", () => resolve(s));
});
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
});
after(() => {
server.close();
try {
rmSync(dir, { recursive: true, force: true });
} catch {
// Windows keeps the database file locked until the process exits.
}
});
test("is answered without signing in, so the login page can look the part too", async () => {
const res = await fetch(`${base}/api/environment`);
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), { environment: { name: "Dev", color: "#0f766e" } });
});
});
+4 -1
View File
@@ -38,6 +38,7 @@ import { api, type CurrentUser, type MaintenanceWindow } from "../api/client";
import { formatRemaining } from "../utils/duration";
import { getTheme, setTheme, type Theme } from "../utils/theme";
import CommandPalette from "../components/CommandPalette";
import { isLightColor, useEnvironment } from "../utils/environment";
type Role = "operator" | "admin";
@@ -163,6 +164,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
const [sidebarOpen, setSidebarOpen] = useState(false);
const [theme, setThemeState] = useState<Theme>(() => getTheme());
const [maintenance, setMaintenance] = useState<MaintenanceWindow[]>([]);
const environment = useEnvironment();
// Everyone sees what's currently silenced, so nobody is left wondering why an alert never came.
useEffect(() => {
@@ -220,7 +222,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
return (
<div className="page">
<aside className="navbar navbar-vertical navbar-expand-lg" data-bs-theme="dark">
<aside className="navbar navbar-vertical navbar-expand-lg" data-bs-theme={environment && isLightColor(environment.color) ? "light" : "dark"}>
<div className="container-fluid">
<button
type="button"
@@ -232,6 +234,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
</button>
<h1 className="navbar-brand navbar-brand-autodark">
<NavLink to="/">Homelab Manager</NavLink>
{environment?.name && <span className="badge ms-2 env-badge">{environment.name}</span>}
</h1>
<div className={`navbar-collapse collapse ${sidebarOpen ? "show" : ""}`}>
<div className="px-3 pt-3 pt-lg-0">
+4
View File
@@ -4,6 +4,10 @@ import { BrowserRouter } from "react-router-dom";
import App from "./App";
import "@tabler/core/dist/css/tabler.min.css";
import "./styles.css";
import { loadEnvironment } from "./utils/environment";
// Dev and production can be told apart (ENVIRONMENT_NAME / ENVIRONMENT_COLOR on the server); do it before anything is drawn.
void loadEnvironment();
// Production only — in dev the worker would just add another layer between Vite and the browser.
if ("serviceWorker" in navigator && import.meta.env.PROD) {
+8 -2
View File
@@ -1,8 +1,14 @@
import { useEnvironment } from "../utils/environment";
export default function Login() {
const environment = useEnvironment();
return (
<div className="login-screen">
<div className="login-card">
<h1>Homelab Manager</h1>
<div className={`login-card ${environment ? "login-card-env" : ""}`}>
<h1>
Homelab Manager
{environment?.name && <span className="badge ms-2 env-badge">{environment.name}</span>}
</h1>
<p>Sign in with your homelab identity provider to continue.</p>
<a className="btn btn-primary w-100" href="/auth/login">
Sign in with Authentik
+18
View File
@@ -34,6 +34,24 @@
margin-bottom: 1.5rem;
}
/* An installation told to look different (ENVIRONMENT_NAME / ENVIRONMENT_COLOR on the server), so a dev copy can't be taken for production. */
html[data-env] .navbar-vertical {
background-color: var(--hlm-env-color) !important;
}
.env-badge {
background-color: #fff;
color: var(--hlm-env-color, #000);
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
vertical-align: middle;
}
.login-card-env {
border-top: 4px solid var(--hlm-env-color);
}
/* Sidebar submenus: a little tighter than Tabler's dropdown rows, so several open groups still fit on one screen. */
.navbar-vertical .dropdown-menu .dropdown-item {
padding-top: 0.3rem;
+64
View File
@@ -0,0 +1,64 @@
import { useEffect, useState } from "react";
/** How this installation looks different from the others (a dev copy next to production), set by ENVIRONMENT_NAME / ENVIRONMENT_COLOR on the server. */
export interface EnvironmentLook {
/** Shown as a badge and in the browser tab; may be empty. */
name: string;
/** A #rrggbb colour. */
color: string;
}
const BASE_TITLE = "Homelab Manager";
let pending: Promise<EnvironmentLook | null> | null = null;
/** Asked once per page load; a failure just means a normal look. */
export function loadEnvironment(): Promise<EnvironmentLook | null> {
if (!pending) {
pending = fetch("/api/environment", { credentials: "same-origin" })
.then((res) => (res.ok ? res.json() : null))
.then((body: { environment?: EnvironmentLook | null } | null) => {
const look = body?.environment;
// The value goes into styles, so only a plain #rrggbb colour is accepted here too.
if (look && typeof look.color === "string" && /^#[0-9a-f]{6}$/i.test(look.color)) {
return { name: typeof look.name === "string" ? look.name : "", color: look.color };
}
return null;
})
.catch(() => null)
.then((look) => {
applyEnvironment(look);
return look;
});
}
return pending;
}
function applyEnvironment(look: EnvironmentLook | null): void {
const root = document.documentElement;
if (!look) return;
root.style.setProperty("--hlm-env-color", look.color);
root.setAttribute("data-env", look.name || "custom");
document.title = look.name ? `[${look.name}] ${BASE_TITLE}` : BASE_TITLE;
document.querySelector('meta[name="theme-color"]')?.setAttribute("content", look.color);
}
/** Whether white text on this colour would be hard to read. */
export function isLightColor(hex: string): boolean {
const n = parseInt(hex.slice(1), 16);
const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
return (0.299 * r + 0.587 * g + 0.114 * b) / 255 > 0.6;
}
/** undefined while it is being asked, null for a normal installation. */
export function useEnvironment(): EnvironmentLook | null | undefined {
const [look, setLook] = useState<EnvironmentLook | null | undefined>(undefined);
useEffect(() => {
let alive = true;
loadEnvironment().then((l) => alive && setLook(l));
return () => {
alive = false;
};
}, []);
return look;
}