- Replace every em-dash in src and server/src with a colon, comma or hyphen - Give every relative import its file extension (.jsx imports of .tsx fixed) - Delete old-historyMock.ts, unused exports, unused CSS utilities, the unused @ alias and the fallback option nothing passed - One copy each of initials, capitalize, byName and the server's marks() - Move the organization, chapter and event hooks from src/data to src/lib - Schema sync always throws on a mismatch (strict was never turned off) - Replace the placeholder README Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
7.3 KiB
JavaScript
187 lines
7.3 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 { 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 home from "./routes/home.js";
|
|
import directory from "./routes/directory.js";
|
|
import blog from "./routes/blog.js";
|
|
import pages from "./routes/pages.js";
|
|
import feedback from "./routes/feedback.js";
|
|
import auth from "./routes/auth.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 { CLIPS_DIR, startClipWorker } from "./clips.js";
|
|
import { UPLOADS_DIR } from "./media.js";
|
|
import { startSessionSweeper } from "./auth.js";
|
|
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
|
|
import { ENTITIES } from "./admin-schema.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}`);
|
|
|
|
/* ── App ─────────────────────────────────────────────────────── */
|
|
|
|
const app = new Hono();
|
|
|
|
app.use("*", logger());
|
|
|
|
/* Headers for every response. Referrer kept to the origin (YouTube
|
|
embeds refuse to play without one); HSTS without includeSubDomains
|
|
so a plain-http dev subdomain keeps working. No CSP yet: pages carry
|
|
an inline window.__NGU_SITE__ script and YouTube, Facebook and Maps
|
|
iframes, so one needs trying in Report-Only first. */
|
|
app.use(
|
|
"*",
|
|
secureHeaders({
|
|
referrerPolicy: "strict-origin-when-cross-origin",
|
|
strictTransportSecurity: "max-age=31536000",
|
|
}),
|
|
);
|
|
|
|
/* 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();
|
|
});
|
|
|
|
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", home);
|
|
app.route("/api", directory);
|
|
app.route("/api", blog);
|
|
|
|
// 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);
|
|
|
|
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 }));
|
|
app.route("/api/admin/panel", panel);
|
|
app.route("/api/auth", auth);
|
|
app.route("/api/admin", admin);
|
|
// Before the entity routes, whose /:entity would claim /media.
|
|
app.route("/api/admin", media);
|
|
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/, ""),
|
|
}),
|
|
);
|
|
|
|
// 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);
|
|
startClipWorker(db);
|
|
console.log(`clips ${CLIPS_DIR}`);
|
|
|
|
app.notFound((c) => c.json({ error: "Not found" }, 404));
|
|
|
|
app.onError((err, c) => {
|
|
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);
|
|
});
|
|
});
|
|
}
|