NGU-Web/server/src/routes/admin-entities.js
Zaldimmar 4066e9ec61 Harden security found in the audit
- Rate limits and IP hashes use the X-Forwarded-For entry nginx adds,
  not the client-supplied first one
- Link preview and feed fetches block IPv4-mapped and other embedded
  IPv6 forms of private addresses (net.BlockList)
- CSRF check on /api writes; security headers and HSTS on every response
- Viewers no longer receive a person's private details (readRole)
- Sessions end 90 days after sign-in however active
- yt-dlp ignores config files and takes the link after --
- Meta tag insert no longer expands $ patterns from record text
- Links with an unsafe scheme draw as text
- Migration 037: leadership lists name published home orgs only
- Ignore *.db-wal, *.db-shm and *.txt

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-28 21:56:49 -05:00

132 lines
4.5 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
ADMIN ENTITY ROUTES
GET /api/admin/options
GET /api/admin/:entity list, filtered and searched
GET /api/admin/:entity/:id row with side tables and children
POST /api/admin/:entity create
PATCH /api/admin/:entity/:id replace the row and its children
DELETE /api/admin/:entity/:id
Mounted alongside the existing admin router, which keeps the
feedback routes. Both sit under the same requireAuth.
:entity is matched against the descriptor map, never
interpolated into SQL from the URL; an unknown name is a 404
before anything touches the database.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { hasRole, requireAuth, requireRole } from "../auth.js";
import { ENTITIES, OPTION_QUERIES } from "../admin-schema.js";
import {
HttpError,
listRows,
readRow,
createRow,
updateRow,
deleteRow,
} from "../admin-crud.js";
const entities = new Hono();
entities.use("*", requireAuth);
const NO_STORE = { "Cache-Control": "no-store" };
function entityOr404(c) {
const entity = ENTITIES[c.req.param("entity")];
if (!entity) throw new HttpError(404, "Unknown entity.");
return entity;
}
/* Saving needs editor, unless the descriptor asks for more
(writeRole): site settings are superadmin-only. requireRole on the
route is the floor; this is the entity's own bar on top. */
function entityForWrite(c) {
const entity = entityOr404(c);
if (entity.writeRole && !hasRole(c.get("user"), entity.writeRole)) {
throw new HttpError(403, "Not allowed.");
}
return entity;
}
/* An extension can ask for more than a sign-in to be read
(readRole): a person's private details need editor. Blanked on
every row sent back, so a write's reply can't leak it either. */
function visible(c, entity, row) {
for (const ext of entity.extensions ?? []) {
if (ext.readRole && !hasRole(c.get("user"), ext.readRole)) row[ext.key] = null;
}
return row;
}
/* Everything the select inputs need, in one request. Small enough
that paging it would cost more than it saves. */
entities.get("/options", (c) => {
const db = c.get("db");
const options = {};
for (const [key, sql] of Object.entries(OPTION_QUERIES)) {
options[key] = db.prepare(sql).all();
}
return c.json({ options }, 200, NO_STORE);
});
entities.get("/:entity", (c) => {
const entity = entityOr404(c);
const { rows, total } = listRows(c.get("db"), entity, c.req.query());
return c.json({ rows, total }, 200, NO_STORE);
});
entities.get("/:entity/:id", (c) => {
const entity = entityOr404(c);
return c.json({ row: visible(c, entity, readRow(c.get("db"), entity, c.req.param("id"))) }, 200, NO_STORE);
});
entities.post("/:entity", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const row = visible(c, entity, createRow(c.get("db"), entity, await json(c)));
console.log(`${entity.key} ${row[entity.idColumn]} created by ${c.get("user").email}`);
return c.json({ row }, 201, NO_STORE);
});
entities.patch("/:entity/:id", requireRole("editor"), async (c) => {
const entity = entityForWrite(c);
const id = c.req.param("id");
const row = visible(c, entity, updateRow(c.get("db"), entity, id, await json(c)));
console.log(`${entity.key} ${id} updated by ${c.get("user").email}`);
return c.json({ row }, 200, NO_STORE);
});
entities.delete("/:entity/:id", requireRole("admin"), (c) => {
const entity = entityOr404(c);
const id = c.req.param("id");
deleteRow(c.get("db"), entity, id);
console.log(`${entity.key} ${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
async function json(c) {
try {
return await c.req.json();
} catch {
throw new HttpError(400, "Expected a JSON body.");
}
}
/* Turn HttpError into a response here rather than letting the
app-level handler flatten everything to a 500. */
entities.onError((err, c) => {
if (err instanceof HttpError) {
return c.json(
err.fields ? { error: err.message, fields: err.fields } : { error: err.message },
err.status,
NO_STORE,
);
}
console.error(err);
return c.json({ error: "Something went wrong." }, 500);
});
export default entities;