Add Site settings: name, description, icons, page titles, indexing
Panel → Site settings (migration 035, superadmins only) edits the site's name, description, preview image, favicon and home-screen icon, each static page's title and intro, and whether search engines may list the site. Every value overrides site.json; a blank one falls back to it. The indexing switch is per database, so the dev server can be off while production is on from one build. The server merges the two (siteFor in pageMeta.js) for page metadata, the sitemap and a new /robots.txt route, and writes the merged wording into each page as window.__NGU_SITE__, which site.ts reads so headings match with no extra request. Entities can now require a higher role to save (writeRole), checked on both sides. Panel is a menu group with Accounts and server, and Site settings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
8ec34ea185
commit
47df7b1fe0
15 changed files with 393 additions and 32 deletions
|
|
@ -904,6 +904,47 @@ const communityPage = {
|
|||
],
|
||||
};
|
||||
|
||||
/* ── Site settings (035_site_settings.sql) ──────────────────────
|
||||
A singleton of overrides for what site.json says: name,
|
||||
description, preview image, icons, search indexing, and static
|
||||
pages' titles and intros. Superadmins only. pageMeta.js merges it
|
||||
over site.json. */
|
||||
const siteSettings = {
|
||||
key: "site_settings",
|
||||
table: "site_settings",
|
||||
idColumn: "id",
|
||||
idKind: "slug",
|
||||
singleton: "site",
|
||||
concurrency: "updated_at",
|
||||
writeRole: "superadmin",
|
||||
|
||||
list: {
|
||||
columns: ["id", "site_name", "updated_at"],
|
||||
filters: [],
|
||||
search: [],
|
||||
order: "id",
|
||||
},
|
||||
|
||||
columns: [
|
||||
text("site_name"),
|
||||
text("description"),
|
||||
text("preview_image"),
|
||||
text("favicon"),
|
||||
text("apple_touch_icon"),
|
||||
enumeration("indexing", ["on", "off"]),
|
||||
],
|
||||
|
||||
children: [
|
||||
{
|
||||
key: "pages",
|
||||
table: "site_setting_pages",
|
||||
owner: { column: "settings_id" },
|
||||
order: "sort_order",
|
||||
columns: [text("path", { required: true }), text("title"), text("description")],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const ENTITIES = {
|
||||
organizations,
|
||||
events,
|
||||
|
|
@ -914,6 +955,7 @@ export const ENTITIES = {
|
|||
front_page: frontPage,
|
||||
blog_posts: blogPosts,
|
||||
community_page: communityPage,
|
||||
site_settings: siteSettings,
|
||||
};
|
||||
|
||||
/* ── Options for the form's select inputs ────────────────────── */
|
||||
|
|
|
|||
|
|
@ -201,6 +201,11 @@ export async function requireAuth(c, next) {
|
|||
export const ROLES = ["viewer", "editor", "admin", "superadmin"];
|
||||
const RANK = { viewer: 1, editor: 2, admin: 3, superadmin: 4 };
|
||||
|
||||
/* Whether a user is at least this rank. A ladder, never equality. */
|
||||
export function hasRole(user, role) {
|
||||
return (RANK[user?.role] ?? 0) >= (RANK[role] ?? Infinity);
|
||||
}
|
||||
|
||||
export function requireRole(...roles) {
|
||||
const need = Math.min(...roles.map((r) => RANK[r] ?? Infinity));
|
||||
return async (c, next) => {
|
||||
|
|
|
|||
62
server/src/migrations/035_site_settings.sql
Normal file
62
server/src/migrations/035_site_settings.sql
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
-- ═══════════════════════════════════════════════════════════════
|
||||
-- 035 SITE SETTINGS
|
||||
--
|
||||
-- What the site says about itself, editable in the admin (Panel →
|
||||
-- Site settings, superadmins only) instead of only in site.json.
|
||||
-- Every column is an override: null means "whatever site.json
|
||||
-- says", so a fresh database behaves exactly as before and the
|
||||
-- built index.html (made from site.json) stays a true fallback for
|
||||
-- when the API is down.
|
||||
--
|
||||
-- site_name the site's name, in every title
|
||||
-- description the default search description
|
||||
-- preview_image the default link-preview image
|
||||
-- favicon the browser-tab icon ('/uploads/…', PNG or SVG)
|
||||
-- apple_touch_icon the home-screen icon on iPhones (PNG, 180px)
|
||||
-- indexing 'on' or 'off': whether search engines may list
|
||||
-- the site. Per database, so the dev server can
|
||||
-- say off while production says on, from one
|
||||
-- build. Null follows site.json's robots.index.
|
||||
--
|
||||
-- site_setting_pages overrides a static page's title and intro
|
||||
-- (site.json's "pages"), one row per page that differs. The path
|
||||
-- must be one of site.json's pages; the admin only offers those.
|
||||
--
|
||||
-- A singleton like front_page: one row, made here, which the admin
|
||||
-- edits and can't delete.
|
||||
--
|
||||
-- PRAGMA user_version; -- reads 34 before this file
|
||||
-- ═══════════════════════════════════════════════════════════════
|
||||
|
||||
CREATE TABLE site_settings (
|
||||
id TEXT PRIMARY KEY CHECK (id = 'site'),
|
||||
site_name TEXT,
|
||||
description TEXT,
|
||||
preview_image TEXT,
|
||||
favicon TEXT,
|
||||
apple_touch_icon TEXT,
|
||||
indexing TEXT CHECK (indexing IN ('on', 'off')),
|
||||
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
||||
) STRICT;
|
||||
|
||||
INSERT INTO site_settings (id) VALUES ('site');
|
||||
|
||||
CREATE TABLE site_setting_pages (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
|
||||
sort_order INTEGER NOT NULL DEFAULT 0,
|
||||
path TEXT NOT NULL, -- '/retreats'
|
||||
title TEXT,
|
||||
description TEXT,
|
||||
UNIQUE (settings_id, path)
|
||||
) STRICT;
|
||||
|
||||
|
||||
-- ── Triggers last (see CLAUDE.md, Migrations) ──
|
||||
|
||||
CREATE TRIGGER site_settings_touch
|
||||
AFTER UPDATE ON site_settings
|
||||
FOR EACH ROW WHEN new.updated_at = old.updated_at
|
||||
BEGIN
|
||||
UPDATE site_settings SET updated_at = datetime('now') WHERE id = new.id;
|
||||
END;
|
||||
|
|
@ -13,9 +13,13 @@
|
|||
|
||||
── Where it comes from ──
|
||||
/site.json (SITE_CONFIG): the site's name, address, default
|
||||
description and image, and each static page's title and
|
||||
description. The pages read the same file for their heading and
|
||||
intro, so the two can't drift.
|
||||
description and image, icons, and each static page's title and
|
||||
description. Laid over it: Panel → Site settings (the
|
||||
site_settings table, 035), where anything set wins and anything
|
||||
blank falls back to site.json. siteFor(db) does the merge. The
|
||||
pages read the same merged values (renderPage writes them into
|
||||
the HTML as window.__NGU_SITE__, see src/lib/site.ts), so a
|
||||
heading and its search title can't drift.
|
||||
The database: records' names, taglines, first paragraphs and
|
||||
images. A blank site description falls back to the front page's
|
||||
subhead.
|
||||
|
|
@ -63,6 +67,57 @@ export function loadSite() {
|
|||
|
||||
const origin = (site) => (site.url ?? "").replace(/\/$/, "");
|
||||
|
||||
/* site.json with the admin's Site settings laid over it: a value set
|
||||
there wins, a blank one falls back. indexing 'on' / 'off' overrides
|
||||
robots.index for this database only. Page overrides apply only to
|
||||
pages site.json knows. */
|
||||
export function siteFor(db) {
|
||||
const base = loadSite();
|
||||
const row = db.prepare(`SELECT * FROM site_settings WHERE id = 'site'`).get() ?? {};
|
||||
|
||||
const pages = { ...(base.pages ?? {}) };
|
||||
const overrides = db
|
||||
.prepare(`SELECT path, title, description FROM site_setting_pages WHERE settings_id = 'site'`)
|
||||
.all();
|
||||
for (const page of overrides) {
|
||||
const known = pages[page.path];
|
||||
if (!known) continue;
|
||||
pages[page.path] = {
|
||||
title: page.title || known.title,
|
||||
description: page.description || known.description,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...base,
|
||||
title: row.site_name || base.title,
|
||||
description: row.description || base.description,
|
||||
openGraph: { ...base.openGraph, image: row.preview_image || base.openGraph?.image },
|
||||
icons: {
|
||||
...base.icons,
|
||||
icon: row.favicon || base.icons?.icon,
|
||||
apple: row.apple_touch_icon || base.icons?.apple,
|
||||
},
|
||||
robots: {
|
||||
...base.robots,
|
||||
index: row.indexing ? row.indexing === "on" : base.robots?.index !== false,
|
||||
},
|
||||
pages,
|
||||
};
|
||||
}
|
||||
|
||||
/* What the browser app reads for headings and titles. */
|
||||
const forBrowser = (site) => ({ title: site.title, pages: site.pages });
|
||||
|
||||
/* robots.txt for this database's setting, as the build writes it. */
|
||||
export function robotsTxt(site) {
|
||||
if (site.robots?.index === false) return "User-agent: *\nDisallow: /\n";
|
||||
return (
|
||||
"User-agent: *\nDisallow: /admin\nDisallow: /api\n" +
|
||||
(site.url ? `\nSitemap: ${origin(site)}/sitemap.xml\n` : "")
|
||||
);
|
||||
}
|
||||
|
||||
/* ── Helpers ───────────────────────────────────────────────── */
|
||||
|
||||
/* Text as a description: the formatting marks content blocks allow
|
||||
|
|
@ -112,6 +167,7 @@ function defaults(site, db, pathname) {
|
|||
type: "website",
|
||||
noindex: false,
|
||||
jsonLd: null,
|
||||
site,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -277,7 +333,7 @@ function blogMeta(site, db, id, meta) {
|
|||
|
||||
/* The metadata for one request path. */
|
||||
export function metaFor(db, rawPath) {
|
||||
const site = loadSite();
|
||||
const site = siteFor(db);
|
||||
// Canonical form: no trailing slash (but "/" itself), no query.
|
||||
const pathname = rawPath.split(/[?#]/)[0].replace(/(.)\/+$/, "$1") || "/";
|
||||
const meta = defaults(site, db, pathname);
|
||||
|
|
@ -352,10 +408,15 @@ const REPLACED = [
|
|||
/<meta\s+(?:name|property)="(?:description|robots|og:[^"]+|twitter:[^"]+)"[^>]*>\s*/gi,
|
||||
/<link\s+rel="canonical"[^>]*>\s*/gi,
|
||||
/<script\s+type="application\/ld\+json"[^>]*>[\s\S]*?<\/script>\s*/gi,
|
||||
/<link\s+rel="(?:icon|apple-touch-icon)"[^>]*>\s*/gi,
|
||||
];
|
||||
|
||||
/* A value for a <script>: JSON with "<" escaped, so nothing in it
|
||||
can end the element early. */
|
||||
const scriptJson = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
|
||||
|
||||
export function renderPage(html, meta) {
|
||||
const site = loadSite();
|
||||
const site = meta.site;
|
||||
let out = html;
|
||||
for (const pattern of REPLACED) out = out.replace(pattern, "");
|
||||
|
||||
|
|
@ -374,12 +435,17 @@ export function renderPage(html, meta) {
|
|||
meta.image && `<meta name="twitter:image" content="${escapeHtml(meta.image)}">`,
|
||||
// "</" can't appear inside the script, or the browser would
|
||||
// end the element there.
|
||||
meta.jsonLd &&
|
||||
`<script type="application/ld+json">${JSON.stringify(meta.jsonLd).replace(/</g, "\\u003c")}</script>`,
|
||||
site.icons?.icon && `<link rel="icon" href="${escapeHtml(site.icons.icon)}">`,
|
||||
site.icons?.apple && `<link rel="apple-touch-icon" href="${escapeHtml(site.icons.apple)}">`,
|
||||
meta.jsonLd && `<script type="application/ld+json">${scriptJson(meta.jsonLd)}</script>`,
|
||||
// Read by src/lib/site.ts before the app's module runs (a plain
|
||||
// script in the head runs during parsing; modules wait).
|
||||
`<script>window.__NGU_SITE__ = ${scriptJson(forBrowser(site))}</script>`,
|
||||
].filter(Boolean);
|
||||
|
||||
// A blocked site (site.json robots.index false) stays blocked on
|
||||
// every page, whatever the record says.
|
||||
// A blocked site (Site settings indexing off, or site.json's
|
||||
// robots.index false) stays blocked on every page, whatever the
|
||||
// record says.
|
||||
if (site.robots?.index === false && !meta.noindex) {
|
||||
tags.splice(2, 0, `<meta name="robots" content="noindex, nofollow">`);
|
||||
}
|
||||
|
|
@ -390,7 +456,7 @@ export function renderPage(html, meta) {
|
|||
/* ── Sitemap ───────────────────────────────────────────────── */
|
||||
|
||||
export function sitemap(db) {
|
||||
const site = loadSite();
|
||||
const site = siteFor(db);
|
||||
const base = origin(site);
|
||||
const day = (value) => (value ? String(value).slice(0, 10) : null);
|
||||
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@
|
|||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { requireAuth, requireRole } from "../auth.js";
|
||||
import { hasRole, requireAuth, requireRole } from "../auth.js";
|
||||
import { ENTITIES, OPTION_QUERIES } from "../admin-schema.js";
|
||||
import {
|
||||
HttpError,
|
||||
|
|
@ -41,6 +41,17 @@ function entityOr404(c) {
|
|||
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;
|
||||
}
|
||||
|
||||
/* Everything the select inputs need, in one request. Small enough
|
||||
that paging it would cost more than it saves. */
|
||||
entities.get("/options", (c) => {
|
||||
|
|
@ -64,14 +75,14 @@ entities.get("/:entity/:id", (c) => {
|
|||
});
|
||||
|
||||
entities.post("/:entity", requireRole("editor"), async (c) => {
|
||||
const entity = entityOr404(c);
|
||||
const entity = entityForWrite(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("editor"), async (c) => {
|
||||
const entity = entityOr404(c);
|
||||
const entity = entityForWrite(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}`);
|
||||
|
|
|
|||
|
|
@ -2,6 +2,9 @@
|
|||
PAGE ROUTES: the site's HTML, with each page's metadata
|
||||
|
||||
GET /sitemap.xml every public, listed page
|
||||
GET /robots.txt this database's indexing setting (Site
|
||||
settings, else site.json), so a dev server
|
||||
can say no while production says yes
|
||||
GET /anything the built index.html, its title, description,
|
||||
preview image, canonical link and structured
|
||||
data filled in for that path (pageMeta.js)
|
||||
|
|
@ -32,7 +35,7 @@ import { fileURLToPath } from "node:url";
|
|||
|
||||
import { Hono } from "hono";
|
||||
|
||||
import { metaFor, renderPage, sitemap } from "../pageMeta.js";
|
||||
import { metaFor, renderPage, robotsTxt, siteFor, sitemap } from "../pageMeta.js";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
|
|
@ -62,6 +65,17 @@ function warnOnce(key, message) {
|
|||
console.error(message);
|
||||
}
|
||||
|
||||
pages.get("/robots.txt", (c) => {
|
||||
let text;
|
||||
try {
|
||||
text = robotsTxt(siteFor(c.get("db")));
|
||||
} catch (err) {
|
||||
warnOnce(`robots:${err.message}`, `pages: can't build robots.txt: ${err.message}`);
|
||||
return c.text("robots.txt isn't available.", 503);
|
||||
}
|
||||
return c.text(text, 200, { "Cache-Control": CACHE });
|
||||
});
|
||||
|
||||
pages.get("/sitemap.xml", (c) => {
|
||||
let xml;
|
||||
try {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue