Move the web application into createApp() so tests can run the real middleware order

index.ts builds the app, runs migrations and starts the schedulers in one go, so nothing
could exercise the app without also starting all that. The app itself (middleware order,
session store, routers) is now createApp() in app.ts; index.ts keeps the startup work and
calls it. No change in behaviour. The test that checks the agent endpoint is mounted ahead
of the 100 KB JSON parser reads app.ts instead.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-06 23:35:33 +02:00
1 parent 5c70956f78
commit 73b86d88de
3 files changed
+127 -101

No files matched your search

+13 -99
View File
@@ -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}`);
});