diff --git a/server/src/app.ts b/server/src/app.ts new file mode 100644 index 0000000..6b5b09d --- /dev/null +++ b/server/src/app.ts @@ -0,0 +1,112 @@ +import express from "express"; +import session from "express-session"; +import FileStoreFactory from "session-file-store"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import { mkdirSync, existsSync } from "node:fs"; +import { env } from "./env.js"; +import { resolveDataPath } from "./paths.js"; +import { authRouter } from "./auth/router.js"; +import { meRouter } from "./routes/me.js"; +import { usersRouter } from "./routes/users.js"; +import { auditLogRouter } from "./routes/auditLog.js"; +import { diagLogRouter } from "./routes/diagLog.js"; +import { secretsRouter } from "./routes/secrets.js"; +import { ipamRouter } from "./routes/ipam.js"; +import { dnsRouter } from "./routes/dns.js"; +import { serversRouter } from "./routes/servers.js"; +import { tasksRouter } from "./routes/tasks.js"; +import { agentReportRouter } from "./routes/agentReport.js"; +import { integrationsRouter } from "./routes/integrations.js"; +import { settingsRouter } from "./routes/settings.js"; +import { searchRouter } from "./routes/search.js"; +import { sessionsRouter } from "./routes/sessions.js"; +import { maintenanceRouter } from "./routes/maintenance.js"; +import { domainsRouter } from "./routes/domains.js"; +import { consistencyRouter } from "./routes/consistency.js"; +import { privacyRouter } from "./routes/privacy.js"; +import { tagsRouter } from "./routes/tags.js"; +import { portsRouter } from "./routes/ports.js"; +import { alertsRouter } from "./routes/alerts.js"; +import { generatorRouter } from "./routes/generator.js"; +import { apiErrorHandler } from "./utils/apiErrorHandler.js"; +import { securityHeaders } from "./utils/securityHeaders.js"; +import { sameOriginGuard } from "./utils/sameOriginGuard.js"; + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const webDist = join(__dirname, "..", "..", "web", "dist"); +const agentDir = join(__dirname, "..", "..", "agent"); + +/** + * The whole web application, ready to listen. It lives apart from index.ts (which also runs migrations and starts the + * schedulers) so the tests can run the real thing — the order of the middleware below is part of what they check. + */ +export function createApp() { + const FileStore = FileStoreFactory(session); + const sessionDir = resolveDataPath(env.sessionDir); + mkdirSync(sessionDir, { recursive: true }); + + const app = express(); + app.disable("x-powered-by"); + app.set("trust proxy", 1); + app.use(securityHeaders); + // The agent endpoint comes first: it reads its own (larger) body, only after checking the token, and an agent has no use for a + // session. It is also the one place a request isn't from a browser, so it isn't subject to the same-origin check below. + app.use("/api/agent/report", agentReportRouter); + // Everything after this is reached with a session cookie, so a request that came from another origin is refused here. + app.use(sameOriginGuard); + app.use(express.json()); + app.use( + session({ + store: new FileStore({ path: sessionDir, logFn: () => {} }), + secret: env.sessionSecret, + resave: false, + saveUninitialized: false, + cookie: { + httpOnly: true, + sameSite: "lax", + secure: env.nodeEnv === "production", + maxAge: 7 * 24 * 60 * 60 * 1000, + }, + }), + ); + + app.get("/health", (_req, res) => res.json({ ok: true })); + + // 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)) { + app.use("/agent", express.static(agentDir)); + } + + app.use("/auth", authRouter); + app.use("/api/me", meRouter); + app.use("/api/users", usersRouter); + app.use("/api/audit-log", auditLogRouter); + app.use("/api/diag-log", diagLogRouter); + app.use("/api/secrets", secretsRouter); + app.use("/api/ipam", ipamRouter); + app.use("/api/dns", dnsRouter); + app.use("/api/servers", serversRouter); + app.use("/api/tasks", tasksRouter); + app.use("/api/integrations", integrationsRouter); + app.use("/api/settings", settingsRouter); + app.use("/api/search", searchRouter); + app.use("/api/sessions", sessionsRouter); + app.use("/api/maintenance", maintenanceRouter); + app.use("/api/domains", domainsRouter); + app.use("/api/consistency", consistencyRouter); + app.use("/api/privacy", privacyRouter); + app.use("/api/tags", tagsRouter); + app.use("/api/ports", portsRouter); + app.use("/api/alerts", alertsRouter); + app.use("/api/generator", generatorRouter); + + if (existsSync(webDist)) { + app.use(express.static(webDist)); + app.get("*", (_req, res) => res.sendFile(join(webDist, "index.html"))); + } + + app.use(apiErrorHandler); + return app; +} diff --git a/server/src/index.ts b/server/src/index.ts index 1ade1a8..93f36e3 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,38 +1,8 @@ import "./loadEnv.js"; -import express from "express"; -import session from "express-session"; -import FileStoreFactory from "session-file-store"; -import { fileURLToPath } from "node:url"; -import { dirname, join } from "node:path"; -import { mkdirSync, existsSync } from "node:fs"; -import { env, warnIfAuthNotConfigured } from "./env.js"; -import { resolveDataPath } from "./paths.js"; +import { env, warnIfAuthNotConfigured, checkSessionSecret } from "./env.js"; +import { createApp } from "./app.js"; import { runMigrations } from "./db/migrate.js"; import { encryptStoredSettingsSecrets } from "./services/settingsStore.js"; -import { authRouter } from "./auth/router.js"; -import { meRouter } from "./routes/me.js"; -import { usersRouter } from "./routes/users.js"; -import { auditLogRouter } from "./routes/auditLog.js"; -import { diagLogRouter } from "./routes/diagLog.js"; -import { secretsRouter } from "./routes/secrets.js"; -import { ipamRouter } from "./routes/ipam.js"; -import { dnsRouter } from "./routes/dns.js"; -import { serversRouter } from "./routes/servers.js"; -import { tasksRouter } from "./routes/tasks.js"; -import { agentReportRouter } from "./routes/agentReport.js"; -import { integrationsRouter } from "./routes/integrations.js"; -import { settingsRouter } from "./routes/settings.js"; -import { searchRouter } from "./routes/search.js"; -import { sessionsRouter } from "./routes/sessions.js"; -import { maintenanceRouter } from "./routes/maintenance.js"; -import { domainsRouter } from "./routes/domains.js"; -import { consistencyRouter } from "./routes/consistency.js"; -import { privacyRouter } from "./routes/privacy.js"; -import { tagsRouter } from "./routes/tags.js"; -import { portsRouter } from "./routes/ports.js"; -import { alertsRouter } from "./routes/alerts.js"; -import { generatorRouter } from "./routes/generator.js"; -import { apiErrorHandler } from "./utils/apiErrorHandler.js"; import { initSecretExpiryScheduler } from "./services/secretExpiryScheduler.js"; import { initTailscaleKeyExpiryScheduler } from "./services/tailscaleKeyExpiryScheduler.js"; import { initLogRetentionScheduler } from "./services/logRetentionScheduler.js"; @@ -42,6 +12,16 @@ import { initPbsVerificationScheduler } from "./services/pbsVerificationSchedule import { initQuietHoursScheduler } from "./services/quietHoursScheduler.js"; import { initHealthScheduler } from "./services/healthScheduler.js"; +{ + // Sessions are signed with this secret. Without one, the app would sign them with a value that's in the source code. + const secret = checkSessionSecret(process.env.SESSION_SECRET, env.nodeEnv); + if (secret.fatal) { + console.error(secret.fatal); + process.exit(1); + } + if (secret.warning) console.warn(secret.warning); +} + warnIfAuthNotConfigured(); await runMigrations(); { @@ -57,72 +37,6 @@ await initPbsVerificationScheduler(); await initQuietHoursScheduler(); await initHealthScheduler(); -const __dirname = dirname(fileURLToPath(import.meta.url)); -const webDist = join(__dirname, "..", "..", "web", "dist"); -const agentDir = join(__dirname, "..", "..", "agent"); - -const FileStore = FileStoreFactory(session); -const sessionDir = resolveDataPath(env.sessionDir); -mkdirSync(sessionDir, { recursive: true }); - -const app = express(); -app.set("trust proxy", 1); -// The agent endpoint comes first: it reads its own (larger) body, only after checking the token, and an agent has no use for a session. -app.use("/api/agent/report", agentReportRouter); -app.use(express.json()); -app.use( - session({ - store: new FileStore({ path: sessionDir, logFn: () => {} }), - secret: env.sessionSecret, - resave: false, - saveUninitialized: false, - cookie: { - httpOnly: true, - sameSite: "lax", - secure: env.nodeEnv === "production", - maxAge: 7 * 24 * 60 * 60 * 1000, - }, - }), -); - -app.get("/health", (_req, res) => res.json({ ok: true })); - -// 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)) { - app.use("/agent", express.static(agentDir)); -} - -app.use("/auth", authRouter); -app.use("/api/me", meRouter); -app.use("/api/users", usersRouter); -app.use("/api/audit-log", auditLogRouter); -app.use("/api/diag-log", diagLogRouter); -app.use("/api/secrets", secretsRouter); -app.use("/api/ipam", ipamRouter); -app.use("/api/dns", dnsRouter); -app.use("/api/servers", serversRouter); -app.use("/api/tasks", tasksRouter); -app.use("/api/integrations", integrationsRouter); -app.use("/api/settings", settingsRouter); -app.use("/api/search", searchRouter); -app.use("/api/sessions", sessionsRouter); -app.use("/api/maintenance", maintenanceRouter); -app.use("/api/domains", domainsRouter); -app.use("/api/consistency", consistencyRouter); -app.use("/api/privacy", privacyRouter); -app.use("/api/tags", tagsRouter); -app.use("/api/ports", portsRouter); -app.use("/api/alerts", alertsRouter); -app.use("/api/generator", generatorRouter); - -if (existsSync(webDist)) { - app.use(express.static(webDist)); - app.get("*", (_req, res) => res.sendFile(join(webDist, "index.html"))); -} - -app.use(apiErrorHandler); - -app.listen(env.port, () => { +createApp().listen(env.port, () => { console.log(`homelab-manager listening on port ${env.port}`); }); diff --git a/server/test/hardening.test.ts b/server/test/hardening.test.ts index 8217fe7..3a835e1 100644 --- a/server/test/hardening.test.ts +++ b/server/test/hardening.test.ts @@ -223,9 +223,9 @@ describe("agent endpoint", () => { const report = (extra: object = {}) => ({ hostname: "agent-host", os_type: "linux", tasks: [], ...extra }); test("is mounted ahead of the app-wide JSON parser and the session store", () => { - const index = readFileSync(join(repoRoot, "server/src/index.ts"), "utf8"); + const index = readFileSync(join(repoRoot, "server/src/app.ts"), "utf8"); const agent = index.indexOf('app.use("/api/agent/report"'); - assert.ok(agent > 0, "agent route not found in index.ts"); + assert.ok(agent > 0, "agent route not found in app.ts"); assert.ok(agent < index.indexOf("app.use(express.json())"), "the agent route must come before the 100 KB JSON parser"); assert.ok(agent < index.indexOf("session({"), "the agent route must come before the session store"); });