diff --git a/.env.example b/.env.example index ddb0e03..b36edf3 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index 35ab0ea..c588e54 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/server/src/app.ts b/server/src/app.ts index 8a97c81..3861dfd 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -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)) { diff --git a/server/src/env.ts b/server/src/env.ts index b326057..37f3832 100644 --- a/server/src/env.ts +++ b/server/src/env.ts @@ -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 = { + 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); }, diff --git a/server/src/index.ts b/server/src/index.ts index 85bf6e2..052d7b8 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -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(); diff --git a/server/test/environment.test.ts b/server/test/environment.test.ts new file mode 100644 index 0000000..b6ffb5f --- /dev/null +++ b/server/test/environment.test.ts @@ -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)", "