v1.4 - added admin page and auth

This commit is contained in:
Zaldimmar 2026-09-25 02:36:49 -05:00
parent 5efdafbb97
commit 1f0aa3078f
29 changed files with 5264 additions and 217 deletions

View file

@ -0,0 +1,111 @@
/* ═══════════════════════════════════════════════════════════════
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 { 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;
}
/* 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: readRow(c.get("db"), entity, c.req.param("id")) }, 200, NO_STORE);
});
entities.post("/:entity", requireRole("admin"), async (c) => {
const entity = entityOr404(c);
const row = 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("admin"), async (c) => {
const entity = entityOr404(c);
const id = c.req.param("id");
const row = 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;

172
server/src/routes/admin.js Normal file
View file

@ -0,0 +1,172 @@
/* ═══════════════════════════════════════════════════════════════
ADMIN ROUTES
Everything under /api/admin requires a session. Writes require
the 'admin' role; a 'viewer' can read and nothing else.
No response from here is cacheable, and none of it should ever
sit in a proxy.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js";
const admin = new Hono();
admin.use("*", requireAuth);
const NO_STORE = { "Cache-Control": "no-store" };
const STATUSES = ["new", "read", "actioned", "archived", "spam"];
const MAX_LIMIT = 200;
const NOTE_LIMIT = 2000;
/* ── GET /api/admin/feedback ─────────────────────────────────────
?status=new one of STATUSES, or omitted for all
?type=broken feedback_type
?q=retreat substring of the message
?before=41 cursor: rows with a lower id than this
?limit=50
───────────────────────────────────────────────────────────── */
admin.get("/feedback", (c) => {
const db = c.get("db");
const { status, type, q, before, limit } = c.req.query();
const where = [];
const params = [];
if (STATUSES.includes(status)) {
where.push("status = ?");
params.push(status);
}
if (type) {
where.push("feedback_type = ?");
params.push(type.slice(0, 40));
}
if (q) {
where.push("message LIKE ?");
params.push(`%${q.slice(0, 100)}%`);
}
if (before && Number.isInteger(Number(before))) {
where.push("id < ?");
params.push(Number(before));
}
const take = Math.min(Number(limit) || 50, MAX_LIMIT);
const rows = db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
FROM feedback
${where.length ? `WHERE ${where.join(" AND ")}` : ""}
ORDER BY id DESC
LIMIT ?`,
)
.all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take;
const page = hasMore ? rows.slice(0, take) : rows;
// Counts are unfiltered on purpose: the tabs should show what's
// waiting overall, not what's left after the current filter.
const counts = Object.fromEntries(STATUSES.map((s) => [s, 0]));
for (const row of db
.prepare("SELECT status, COUNT(*) AS n FROM feedback GROUP BY status")
.all()) {
counts[row.status] = row.n;
}
return c.json(
{
feedback: page,
counts,
nextCursor: hasMore ? page[page.length - 1].id : null,
},
200,
NO_STORE,
);
});
/* ── PATCH /api/admin/feedback/:id ───────────────────────────────
{ status?, admin_note? } — either, both, partial.
───────────────────────────────────────────────────────────── */
admin.patch("/feedback/:id", requireRole("admin"), async (c) => {
const id = Number(c.req.param("id"));
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
let body;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Expected a JSON body." }, 400);
}
const sets = [];
const params = [];
if (body.status !== undefined) {
if (!STATUSES.includes(body.status)) {
return c.json({ error: "Unknown status." }, 422);
}
sets.push("status = ?");
params.push(body.status);
}
if (body.admin_note !== undefined) {
const note = String(body.admin_note).trim().slice(0, NOTE_LIMIT);
sets.push("admin_note = ?");
params.push(note || null);
}
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
const result = db_update(c.get("db"), id, sets, params);
if (!result) return c.json({ error: "No such feedback." }, 404);
console.log(`feedback #${id} updated by ${c.get("user").email}`);
return c.json({ feedback: result }, 200, NO_STORE);
});
function db_update(db, id, sets, params) {
const changed = db
.prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`)
.run(...params, id);
if (changed.changes === 0) return null;
return db
.prepare(
`SELECT id, created_at, feedback_type, message, name, email,
page_path, section_id, status, admin_note
FROM feedback WHERE id = ?`,
)
.get(id);
}
/* ── DELETE /api/admin/feedback/:id ──────────────────────────────
Actually gone. Marking something 'spam' is the reversible
option and should be the habit; this is for the cases where
the content itself shouldn't stay on disk.
───────────────────────────────────────────────────────────── */
admin.delete("/feedback/:id", requireRole("admin"), (c) => {
const id = Number(c.req.param("id"));
if (!Number.isInteger(id)) return c.json({ error: "Bad id." }, 400);
const result = c
.get("db")
.prepare("DELETE FROM feedback WHERE id = ?")
.run(id);
if (result.changes === 0) return c.json({ error: "No such feedback." }, 404);
console.log(`feedback #${id} deleted by ${c.get("user").email}`);
return c.body(null, 204);
});
export default admin;

99
server/src/routes/auth.js Normal file
View file

@ -0,0 +1,99 @@
/* ═══════════════════════════════════════════════════════════════
AUTH ROUTES
POST /api/auth/login email + password → session cookie
POST /api/auth/logout deletes the session row and cookie
GET /api/auth/me who am I, or 401
Three deliberate choices:
Login is rate limited where it's mounted, and answers wrong
password and unknown account identically. Telling an attacker
which addresses exist is free reconnaissance.
A failed login still runs a hash. Otherwise the response time
itself says whether the account exists.
Nothing here creates accounts. See admin-cli.js.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import {
createSession,
destroySession,
currentUser,
hashPassword,
verifyPassword,
} from "../auth.js";
const auth = new Hono();
// A real hash to compare against when the account doesn't exist,
// so both paths cost the same. Computed once at import.
const DUMMY_HASH = hashPassword("this password is never correct");
const NO_STORE = { "Cache-Control": "no-store" };
auth.post("/login", async (c) => {
let body;
try {
body = await c.req.json();
} catch {
return c.json({ error: "Expected a JSON body." }, 400);
}
const email = String(body.email ?? "").trim().toLowerCase().slice(0, 254);
const password = String(body.password ?? "");
if (!email || !password) {
return c.json({ error: "Email and password are required." }, 400);
}
const db = c.get("db");
const user = db
.prepare(
`SELECT id, email, name, role, password_hash, is_active
FROM admin_users
WHERE email = ?`,
)
.get(email);
const ok =
user && user.is_active === 1
? verifyPassword(password, user.password_hash)
: (verifyPassword(password, DUMMY_HASH), false);
if (!ok) {
console.warn(`login failed for ${email}`);
return c.json({ error: "That email and password don't match." }, 401);
}
createSession(db, c, user.id);
db.prepare("UPDATE admin_users SET last_login_at = datetime('now') WHERE id = ?").run(
user.id,
);
console.log(`login ${user.email}`);
return c.json(
{ user: { id: user.id, email: user.email, name: user.name, role: user.role } },
200,
NO_STORE,
);
});
auth.post("/logout", (c) => {
destroySession(c.get("db"), c);
return c.body(null, 204);
});
auth.get("/me", (c) => {
const user = currentUser(c.get("db"), c);
if (!user) return c.json({ error: "Not signed in." }, 401, NO_STORE);
return c.json({ user }, 200, NO_STORE);
});
export default auth;

141
server/src/routes/people.js Normal file
View file

@ -0,0 +1,141 @@
/* ═══════════════════════════════════════════════════════════════
PEOPLE ROUTES — read-only, mounted under /api
GET /teams/:id/people current public members of a team
GET /people?ids=a,b,c named people, any order
The team route reads v_org_leadership, which already decides who
counts as current and public — affiliation still open, marked
public, person published. Restating those conditions here is how
they drift apart.
That view is affiliation-driven, so it can't serve the lookup
route: a person with no affiliations would vanish, and one with
several would appear more than once. The lookup reads people
directly and returns no title, because a bare slug names no seat.
Photos are filenames, as everywhere else in this API. The
component decides where they live.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { asBool } from "../shape.js";
const people = new Hono();
const CACHE = "public, max-age=60, stale-while-revalidate=300";
const json = (c, body) => c.json(body, 200, { "Cache-Control": CACHE });
const marks = (n) => Array(n).fill("?").join(",");
/* How many slugs one request may name. Keeps the URL sane. */
const MAX_IDS = 50;
function shapePerson(row) {
return {
id: row.id ?? row.person_id,
name: row.display_name,
// Only the team route knows a seat; the lookup route doesn't.
title: row.title ?? null,
tagline: row.tagline,
pronouns: row.pronouns,
photo: row.photo,
location_label: row.location_label,
public_email: row.public_email,
org: row.primary_org_id
? { id: row.primary_org_id, name: row.primary_org_name }
: null,
bio: splitParagraphs(row.bio),
role: row.role ?? null,
is_owner: row.is_owner === undefined ? false : asBool(row.is_owner),
};
}
/* people.bio is one run of prose with blank lines between
paragraphs — unrelated to shape.js's paragraphs(), which turns
content_block rows into text. */
function splitParagraphs(text) {
if (!text) return null;
const parts = text
.split(/\n\s*\n/)
.map((part) => part.trim())
.filter(Boolean);
return parts.length ? parts : null;
}
/* ── One team's people ─────────────────────────────────────── */
people.get("/teams/:id/people", (c) => {
const db = c.get("db");
const id = c.req.param("id");
const team = db
.prepare(
`SELECT id, org_id, name, tagline, color, logo
FROM teams
WHERE id = ? AND is_published = 1`,
)
.get(id);
if (!team) return c.json({ error: "No such team" }, 404);
// The view orders by org first, which isn't what a single team
// wants, so the order is restated here.
const rows = db
.prepare(
`SELECT * FROM v_org_leadership
WHERE team_id = ?
ORDER BY is_owner DESC,
sort_order,
COALESCE(sort_name, display_name),
display_name`,
)
.all(id);
return json(c, { team, people: rows.map(shapePerson) });
});
/* ── People by id ──────────────────────────────────────────────
For hand-picked lists in a section. Order is the caller's, so
there's no ORDER BY here.
───────────────────────────────────────────────────────────── */
people.get("/people", (c) => {
const db = c.get("db");
const ids = [
...new Set(
(c.req.query("ids") ?? "")
.split(",")
.map((part) => part.trim())
.filter(Boolean),
),
].slice(0, MAX_IDS);
if (ids.length === 0) return json(c, { people: [] });
const rows = db
.prepare(
`SELECT p.id,
p.display_name,
p.pronouns,
p.photo,
p.tagline,
p.location_label,
p.public_email,
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM people p
LEFT JOIN organizations o ON o.id = p.primary_org_id
WHERE p.id IN (${marks(ids.length)})
AND p.is_published = 1`,
)
.all(...ids);
return json(c, { people: rows.map(shapePerson) });
});
export default people;