NGU-Web/server/src/index.js
Aidan Dona f1a0b06ac2 Page management, step 3: section types with their own settings; the front page as sections
Migration 083 gives the section types that need more than blocks their
own tables (hero, slides, countdown, stats, paths, featured cards, the
Community blog's slots, pinned posts and feeds) and turns the front page
into Home's sections: the hero, then its bands in order. Any section can
be hidden. The Front page editor, its tables and the Community page's
are gone; /api/front-page and /api/community-blog fold into the page's
sections (sectionData.js). The admin engine reads and writes a child
collection's own side tables and gated nested collections.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 00:34:56 -05:00

302 lines
12 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
NGU API
Binds to localhost only. nginx is the only thing that talks to
it, which is what lets the routes trust X-Forwarded-For and skip
CORS entirely, in production the API and the site share an
origin, and in development Vite proxies /api so they share one
there too.
═══════════════════════════════════════════════════════════════ */
import { mkdir } from "node:fs/promises";
import { serve } from "@hono/node-server";
import { serveStatic } from "@hono/node-server/serve-static";
import { Hono } from "hono";
import { bodyLimit } from "hono/body-limit";
import { HTTPException } from "hono/http-exception";
import { csrf } from "hono/csrf";
import { logger } from "hono/logger";
import { secureHeaders } from "hono/secure-headers";
import { openDatabase, migrate } from "./db.js";
import { rateLimit } from "./rateLimit.js";
import content from "./routes/content.js";
import people from "./routes/people.js";
import history from "./routes/history.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import sitePages from "./routes/sitePages.js";
import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
import auth from "./routes/auth.js";
import account from "./routes/account.js";
import profiles from "./routes/profiles.js";
import admin from "./routes/admin.js";
import panel from "./routes/panel.js";
import adminEntities from "./routes/admin-entities.js";
import media from "./routes/media.js";
import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import files from "./routes/files.js";
import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, requireStaff, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
import { ENTITIES } from "./admin-schema.js";
import { previewDrafts } from "./drafts.js";
const HOST = process.env.HOST ?? "127.0.0.1";
const PORT = Number(process.env.PORT ?? 3001);
const DB_PATH = process.env.DB_PATH ?? "./ngu.db";
/* ── Boot ────────────────────────────────────────────────────── */
const db = await openDatabase(DB_PATH);
const version = migrate(db);
syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
// In the background: pages fall back to the full file until it's done.
writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`))
.catch((err) => console.warn(`uploads: small copies failed: ${err.message}`));
/* ── App ─────────────────────────────────────────────────────── */
const app = new Hono();
// One log line per admin request, for the record of who did what.
// Public traffic is left to nginx's access log: logging every request
// here too would double the lines and, under a spike, cost the event
// loop a synchronous write each.
app.use("/api/admin/*", logger());
/* A newsletter's countdown picture is shown inside other sites'
webmail, which the same-origin resource policy set below would
refuse. Registered first so it runs last, after secureHeaders. */
app.use("/api/countdown/*", async (c, next) => {
await next();
c.res.headers.set("Cross-Origin-Resource-Policy", "cross-origin");
});
/* Headers for every response. Referrer kept to the origin (YouTube
embeds refuse to play without one). No HSTS here: nginx sends it on
everything, including the files it serves from disk
(docs/security-headers.md).
The Content-Security-Policy is Report-Only for now: nothing is
blocked, and each thing it would have blocked is logged by
/api/csp-report (journalctl -u ngu-api). Once a while of real use
logs nothing unexpected, switch contentSecurityPolicyReportOnly to
contentSecurityPolicy. 'unsafe-inline' scripts cover the page's
window.__SITE__ and the theme script in index.html. */
const EMBEDS = [
"https://www.youtube-nocookie.com",
"https://www.youtube.com",
"https://www.facebook.com",
"https://player.vimeo.com",
"https://www.google.com",
"https://maps.google.com",
"https://*.churchcenter.com",
"https://*.churchcenteronline.com",
];
app.use(
"*",
secureHeaders({
referrerPolicy: "strict-origin-when-cross-origin",
strictTransportSecurity: false,
contentSecurityPolicyReportOnly: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'", "https://js.churchcenter.com"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
mediaSrc: ["'self'"],
fontSrc: ["'self'"],
connectSrc: ["'self'"],
frameSrc: EMBEDS,
frameAncestors: ["'self'"],
baseUri: ["'self'"],
formAction: ["'self'"],
objectSrc: ["'none'"],
reportUri: "/api/csp-report",
},
}),
);
/* The public JSON writes read their whole body before trimming it,
so each is capped well above its longest real body (a 5000
character message) and far below nginx's limit. */
const smallBody = bodyLimit({ maxSize: 64 * 1024, onError: (c) => c.json({ error: "That's too long." }, 413) });
for (const path of ["/api/csp-report", "/api/feedback", "/api/auth/login", "/api/account/accept", "/api/account/claim", "/api/account/profile"]) app.use(path, smallBody);
/* What the policy above would have blocked. Browsers post these on
their own; a short line per report is plenty to go on. */
app.use("/api/csp-report", rateLimit({ windowMs: 60_000, max: 30 }));
app.post("/api/csp-report", async (c) => {
const text = (await c.req.text()).slice(0, 4000);
try {
const report = JSON.parse(text)["csp-report"] ?? {};
const field = (name) => logSafe(report[name] ?? "?", 150);
console.warn(
`csp ${field("violated-directive")} blocked ${field("blocked-uri")} on ${field("document-uri")}`,
);
} catch {
// Not a report; nothing to log.
}
return c.body(null, 204);
});
/* Refuse a form-style write (text/plain, form or multipart body)
that another site sent, including a sibling subdomain, which
SameSite=Lax cookies don't stop. Browsers mark their own requests
Sec-Fetch-Site: same-origin; older ones fall back to Origin, judged
by host because nginx speaks plain http to this service. JSON
bodies can't be sent cross-origin without a CORS preflight, which
this API never answers. */
app.use(
"/api/*",
csrf({
origin: (origin, c) => {
try {
return new URL(origin).host === c.req.header("host");
} catch {
return false;
}
},
}),
);
app.use("*", async (c, next) => {
c.set("db", db);
await next();
});
// A draft's preview (drafts.js): a public read from a signed-in
// viewer with X-Draft-Preview answers with that draft applied.
app.use("/api/*", previewDrafts);
app.get("/api/health", (c) =>
c.json({ ok: true, schema: version, driver: db.driverName }),
);
app.route("/api", content);
app.route("/api", people);
app.route("/api", history);
app.route("/api", directory);
app.route("/api", blog);
app.route("/api", sitePages);
// Opened by everyone a newsletter goes to, often through one mail
// proxy's address, so looser than the rest; each picture is kept for
// its minute (routes/countdown.js).
app.use("/api/countdown/*", rateLimit({ windowMs: 60_000, max: 600 }));
app.route("/api", countdown);
// Tighter limit on the write path than anything else gets.
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));
app.route("/api/feedback", feedback);
// Requests carry files: fewer again.
app.use("/api/requests", rateLimit({ windowMs: 10 * 60_000, max: 5 }));
app.route("/api/requests", requests);
app.use("/api/auth/login", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
// Looser than a password guess: each Google sign-in is two requests,
// and Google has already checked the person by the second.
app.use("/api/auth/google/*", rateLimit({ windowMs: 15 * 60_000, max: 40 }));
// The whole admin is for viewer and up; a profile account (member)
// is signed in but kept out. Each router still checks its own.
app.use("/api/admin/*", requireStaff);
app.route("/api/admin/panel", panel);
app.route("/api/auth", auth);
// A profile account's own page (076); setting a password from an
// invite is held to the login's pace.
app.use("/api/account/accept", rateLimit({ windowMs: 15 * 60_000, max: 10 }));
app.use("/api/account/photo", rateLimit({ windowMs: 15 * 60_000, max: 20 }));
app.route("/api/account", account);
app.route("/api/admin", admin);
app.route("/api/admin", profiles);
// Before the entity routes, whose /:entity would claim /media.
app.route("/api/admin", media);
app.route("/api/admin", imports);
app.route("/api/admin", files);
app.route("/api/admin", clips);
app.route("/api/admin", adminEntities);
/* ── Uploads ───────────────────────────────────────────────────
In production nginx serves /uploads/ straight from disk and
never passes it here. This is for development, where Vite
proxies /uploads to the API. The headers match the nginx
block's: an uploaded SVG opened on its own can't run script.
───────────────────────────────────────────────────────────── */
app.use("/uploads/*", async (c, next) => {
await next();
c.header("X-Content-Type-Options", "nosniff");
c.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox");
});
app.use(
"/uploads/*",
serveStatic({
root: UPLOADS_DIR,
rewriteRequestPath: (p) => p.replace(/^\/uploads/, ""),
}),
);
// Short links, /go/<id> (routes/redirects.js); an unknown one falls
// through to the pages below.
app.route("/", redirects);
// Last: every other GET that isn't /api is a page of the site, sent
// with its metadata filled in (routes/pages.js).
app.route("/", pages);
startSessionSweeper(db);
startGroupSync(db);
startClipWorker(db);
startAnalyticsReports(db);
console.log(`clips ${CLIPS_DIR}`);
app.notFound((c) => c.json({ error: "Not found" }, 404));
app.onError((err, c) => {
// A deliberate refusal (the CSRF check's 403, say) is an answer,
// not a crash: send it as it is and keep it out of the error log.
if (err instanceof HTTPException) return err.getResponse();
console.error(err);
// Never leak internals to the browser.
return c.json({ error: "Something went wrong." }, 500);
});
/* ── Serve ───────────────────────────────────────────────────── */
const server = serve({ fetch: app.fetch, hostname: HOST, port: PORT }, (info) =>
console.log(`listening http://${info.address}:${info.port}`),
);
/* ── Shutdown ──────────────────────────────────────────────────
systemd sends SIGTERM on stop and restart. Closing the handle
flushes the WAL cleanly, which saves a recovery pass on the
next boot.
───────────────────────────────────────────────────────────── */
for (const signal of ["SIGTERM", "SIGINT"]) {
process.on(signal, () => {
console.log(`${signal}, shutting down`);
server.close(() => {
try {
db.close();
} catch {
/* nothing useful to do here */
}
process.exit(0);
});
});
}