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:
1 parent
5c70956f78
commit
73b86d88de
3 files changed
+127
-101
No files matched your search
@@ -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;
|
||||
}
|
||||
+13
-99
@@ -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}`);
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user