From 1ff3522c5600809195fe935cf7c0a3ee83a55e37 Mon Sep 17 00:00:00 2001 From: Pablo Volenski Date: Tue, 6 Oct 2026 11:55:41 +0000 Subject: [PATCH 1/2] A superadministrator above the responsable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit You asked for a super-admin, and most of it already existed as the `owner` role — labelled «Responsable», seeded from BOARD_OWNER, already the only account that could create an admin, demote one, erase anybody or hand the role on, with a partial unique index making "exactly one" a database rule. You chose a genuine fifth tier anyway, and there is a reading in which that is the better answer, so this builds it with that reading made explicit: superadministrador — the platform: admin accounts, the look, the identity responsable — the association: members, moderators, invitations The split is worth more than a rename because of where this is going. Installed for a second organisation, the superadministrator is whoever maintains the box and the responsable is their president — so the responsable chair is safe to hand to a customer, and an admin account is not theirs to grant. Both chairs are unreachable, for different reasons. The superadministrator because there is nothing above them. The responsable because the chair belongs to the association: a platform administrator quietly removing the president of the organisation they host is exactly the move two chairs exist to prevent. Each steps down by handing their own chair on, and whoever gives one up becomes an administrator — there is no role above the one they just gave away. Migration 7 is the rebuild migration 4 already did, for the same reason (SQLite cannot alter a CHECK), and it promotes the existing owner — Pablo — to superadministrator, leaving the responsable chair empty for the association to fill. Nothing is erased; you offered and it was not needed. Two things in here would have shipped silently without a test looking for them: `_seed_superadmin` ends `ON CONFLICT(gitea_login) DO UPDATE SET role = …`. That line was right while owner was the top of the tree. Left as it was, it would have matched BOARD_OWNER's login and demoted the superadministrator back to owner **on every container restart** — a privilege reduction caused by nothing anybody did, freeing the chair for somebody else. It takes a second start-up to catch, so the test starts the app three times. And seven places outside the role modules asked "is this person at least an admin" as a literal `("owner", "admin")` tuple — the wall's delete, the editor's page collection, the calendar's edit flag, the dashboard, the moderation predicate. Every one of them silently excluded the superadministrator the moment a tier appeared above owner. They are now one ordered LADDER and one `is_at_least`, so the next tier is a word in a list rather than an audit. Marca moves from admin-only to superadmin-only, which is the distinction you asked for: the look and the identity are the platform's. 564 tests pass, including the predicate table per actor and target, each of the four doors into "make an admin" closed against an admin and against the responsable, and both single-chair indexes surviving the rebuild. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn --- apps/board/app.py | 4 + apps/board/board.py | 4 +- apps/board/brand.py | 16 +- apps/board/content.py | 6 +- apps/board/db.py | 44 +++-- apps/board/events.py | 6 +- apps/board/home.py | 4 +- apps/board/members.py | 123 +++++++++--- apps/board/migrations.py | 65 ++++++ apps/board/schema.sql | 21 +- apps/board/security.py | 56 +++++- apps/board/submissions.py | 4 +- apps/board/templates/gestion.html | 2 + apps/board/templates/member.html | 61 +++--- apps/board/templates/members.html | 9 +- apps/board/tests/conftest.py | 16 +- apps/board/tests/test_brand.py | 38 ++-- apps/board/tests/test_events.py | 48 ++--- apps/board/tests/test_invites.py | 36 ++-- apps/board/tests/test_members.py | 285 +++++++++++++++++++++------ apps/board/tests/test_messages.py | 8 +- apps/board/tests/test_migrations.py | 109 ++++++++-- apps/board/tests/test_profiles.py | 12 +- apps/board/tests/test_reactions.py | 8 +- apps/board/tests/test_submissions.py | 8 +- docs/server-setup.md | 84 +++++--- 26 files changed, 801 insertions(+), 276 deletions(-) diff --git a/apps/board/app.py b/apps/board/app.py index 8f9d53d..61f1ba5 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -118,6 +118,10 @@ def create_app(overrides: dict | None = None) -> Flask: # For _person.html: the one login with no page behind it. A literal in the # template would be the same string written twice, in two languages. app.jinja_env.globals["tombstone_login"] = TOMBSTONE_LOGIN + # For member.html's role picker. The template asking the predicate is what + # keeps the picker from offering a role the handler will refuse — with two + # levels above admin, a hardcoded list can only be right for one of them. + app.jinja_env.globals["assignable_roles"] = members.assignable_roles @app.context_processor def _year(): diff --git a/apps/board/board.py b/apps/board/board.py index e793907..80b5cb1 100644 --- a/apps/board/board.py +++ b/apps/board/board.py @@ -21,7 +21,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect, from . import auth, uploads from .db import get_db from .render import excerpt, to_html -from .security import admin_required, login_required +from .security import admin_required, is_at_least, login_required bp = Blueprint("board", __name__) @@ -31,7 +31,7 @@ BODY_MAX = 20_000 def is_admin() -> bool: - return g.member["role"] in ("owner", "admin") + return is_at_least(g.member["role"], "admin") def may_delete(row) -> bool: diff --git a/apps/board/brand.py b/apps/board/brand.py index 8b84ea5..d52bf93 100644 --- a/apps/board/brand.py +++ b/apps/board/brand.py @@ -12,6 +12,14 @@ drifts from it. That is what retires the comment: not by merging the two files they are served by different things and each has to stand on its own — but by making a divergence fail the build instead of going unnoticed for a month. +### Whose screen this is + +**The superadministrator's, not an admin's.** The look and the identity are the +platform's, and an admin is the association's committee — the same line that +makes an admin account the superadministrator's to grant. An admin who wants the +colours changed asks the person who installed this, which is the correct +conversation to be having. + ### The two destinations One form, saved to two places, because the two halves cannot read the same @@ -47,7 +55,7 @@ from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, from . import gitea, uploads from .db import get_db -from .security import admin_required +from .security import superadmin_required bp = Blueprint("brand", __name__) @@ -364,7 +372,7 @@ def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]): # --- routes ---------------------------------------------------------------- @bp.route("/gestion/marca", methods=["GET", "POST"]) -@admin_required +@superadmin_required def edit(): if request.method == "GET": state = current() @@ -439,7 +447,7 @@ def _store(stored: dict, css: str, logo, favicon, state: dict) -> None: @bp.route("/gestion/marca/publicar", methods=["POST"]) -@admin_required +@superadmin_required def publish(): """Try the commits again after the git server was unreachable.""" if _publish(): @@ -448,7 +456,7 @@ def publish(): @bp.route("/gestion/marca/restaurar", methods=["POST"]) -@admin_required +@superadmin_required def restore(): """Back to the colours the site was built with. diff --git a/apps/board/content.py b/apps/board/content.py index d36609c..bbcdd2b 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect, from . import gitea from .db import get_db from .render import to_html -from .security import moderator_required +from .security import is_at_least, moderator_required # One list of accepted formats for the whole app, kept in the module that # knows what each one looks like on the wire, so the editor and the board # cannot drift apart about what a picture is. @@ -233,7 +233,7 @@ def _collection_or_404(collection: str) -> dict: if collection not in COLLECTIONS: abort(404) meta = COLLECTIONS[collection] - if meta["role"] == "admin" and g.member["role"] not in ("owner", "admin"): + if meta["role"] == "admin" and not is_at_least(g.member["role"], "admin"): abort(403) return meta @@ -242,7 +242,7 @@ def visible_collections() -> dict: """The collections this member may write to, for the tabs. A tab that only ever produces a 403 is worse than no tab.""" return {name: meta for name, meta in COLLECTIONS.items() - if meta["role"] != "admin" or g.member["role"] in ("owner", "admin")} + if meta["role"] != "admin" or is_at_least(g.member["role"], "admin")} def _name_or_404(name: str) -> str: diff --git a/apps/board/db.py b/apps/board/db.py index a247864..95de582 100644 --- a/apps/board/db.py +++ b/apps/board/db.py @@ -65,7 +65,7 @@ def init_db(app) -> None: for step in migrations.apply(db): app.logger.info("Applied migration %s", step) _ensure_tombstone(db) - _seed_owner(db, app) + _seed_superadmin(db, app) finally: db.close() @@ -79,35 +79,49 @@ def _ensure_tombstone(db: sqlite3.Connection) -> None: ) -def _seed_owner(db: sqlite3.Connection, app) -> None: - """Create the first owner from BOARD_OWNER, once. +def _seed_superadmin(db: sqlite3.Connection, app) -> None: + """Create the first superadministrator from BOARD_OWNER, once. - Deliberately refuses to change an existing owner. Were this to overwrite, - anyone who could edit the environment could hand themselves ownership by - restarting the container — which is a quieter privilege escalation than it - looks, since editing a compose file draws far less attention than asking - the owner for access. + Still `BOARD_OWNER` rather than a new name: it is the variable the server's + `.env` already carries, and an install that has to edit its environment to + survive an upgrade is an install that breaks on upgrade. + + Deliberately refuses to change an existing superadministrator. Were this to + overwrite, anyone who could edit the environment could hand themselves the + platform by restarting the container — a quieter privilege escalation than + it looks, since editing a compose file draws far less attention than asking + for access. + + **The `ON CONFLICT` below is the half worth reading twice.** It used to end + `SET role = 'owner'`, which was right while owner was the top of the tree. + Left that way after migration 7 it would have found the superadministrator's + login, matched the conflict, and demoted them back to owner on every + container restart — a privilege *reduction* arriving at the least convenient + moment and attributable to nothing anybody did. `members_one_superadmin` + would then have let somebody else take the chair. """ login = (app.config.get("OWNER_LOGIN") or "").strip() - existing = db.execute("SELECT gitea_login FROM members WHERE role = 'owner'").fetchone() + existing = db.execute( + "SELECT gitea_login FROM members WHERE role = 'superadmin'").fetchone() if existing: if login and existing["gitea_login"].lower() != login.lower(): app.logger.warning( - "BOARD_OWNER is %r but the owner is %r; leaving it alone. " - "Transfer ownership from inside the app instead.", + "BOARD_OWNER is %r but the superadministrator is %r; leaving it " + "alone. Hand the platform on from inside the app instead.", login, existing["gitea_login"], ) return if not login: - app.logger.warning("No owner yet and BOARD_OWNER is unset — nobody can sign in.") + app.logger.warning("No superadministrator yet and BOARD_OWNER is unset — " + "nobody can sign in.") return db.execute( """INSERT INTO members (gitea_login, display_name, role, active) - VALUES (?, ?, 'owner', 1) - ON CONFLICT(gitea_login) DO UPDATE SET role = 'owner', active = 1""", + VALUES (?, ?, 'superadmin', 1) + ON CONFLICT(gitea_login) DO UPDATE SET role = 'superadmin', active = 1""", (login, login), ) - app.logger.info("Seeded %r as owner.", login) + app.logger.info("Seeded %r as superadministrator.", login) diff --git a/apps/board/events.py b/apps/board/events.py index e270a0d..a4e0e97 100644 --- a/apps/board/events.py +++ b/apps/board/events.py @@ -32,7 +32,7 @@ from flask import (Blueprint, Response, abort, flash, g, redirect, from . import content, gitea, uploads from .db import get_db from .render import to_html -from .security import admin_required, login_required +from .security import admin_required, is_at_least, login_required bp = Blueprint("events", __name__) @@ -129,7 +129,7 @@ def month(): this_month=f"{today.year:04d}-{today.month:02d}", today=today.day if (today.year, today.month) == (year, number) else 0, public_missing=public_missing, - may_edit=g.member["role"] in ("owner", "admin"), + may_edit=is_at_least(g.member["role"], "admin"), ) @@ -140,7 +140,7 @@ def show(event_id: int): return render_template("event.html", event=row, body_html=to_html(row["body_md"] or ""), when=_spoken_date(row["starts_on"]), - may_edit=g.member["role"] in ("owner", "admin")) + may_edit=is_at_least(g.member["role"], "admin")) @bp.route("/calendario/.ics") diff --git a/apps/board/home.py b/apps/board/home.py index 8683d1f..4fa6ec4 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -18,7 +18,7 @@ from flask import Blueprint, g, jsonify, render_template, request, url_for from . import submissions from .db import TOMBSTONE_LOGIN, get_db from .render import excerpt, to_html -from .security import admin_required, csrf_token, login_required +from .security import admin_required, csrf_token, is_at_least, login_required bp = Blueprint("home", __name__) @@ -126,7 +126,7 @@ def session_state(): {"label": "Publicaciones", "url": url_for("submissions.index")}, {"label": "Calendario", "url": url_for("events.month")}, ] - if g.member["role"] in ("owner", "admin"): + if is_at_least(g.member["role"], "admin"): sections.append({"label": "Gestión", "url": url_for("home.gestion")}) return _no_store(jsonify({ diff --git a/apps/board/members.py b/apps/board/members.py index d0556e8..c7cfe4f 100644 --- a/apps/board/members.py +++ b/apps/board/members.py @@ -1,11 +1,14 @@ """Members and roles. -Four roles, and the rules between them are short enough to state in full: +Five roles, and the rules between them are short enough to state in full: -* exactly one **owner**, who creates and removes admins and can hand ownership - on; nobody can deactivate or demote them, including themselves -* **admins** create, deactivate and promote members, moderate the board, and - publish and edit the static pages of the public site +* exactly one **superadministrador**, who runs the platform: admin accounts, + the look, the identity and the system tools. Nobody can deactivate, demote or + erase them, including themselves +* exactly one **responsable**, who runs the association: members, moderators + and invitations. They cannot touch an admin, the look or the identity +* **admins** create, deactivate and promote members and moderators, moderate + the board, and publish and edit the static pages of the public site * **moderators** approve or reject what members propose for the public site, and publish their own posts without waiting for anybody. They have no power over people: moderating content is not the same authority, and giving one the @@ -30,7 +33,8 @@ from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, from . import auth, invites, mail, messages, profiles, uploads from .db import TOMBSTONE_LOGIN, get_db from .render import to_html -from .security import admin_required, login_required, owner_required +from .security import (admin_required, login_required, owner_required, + superadmin_required) bp = Blueprint("members", __name__) @@ -41,20 +45,35 @@ LOGIN_RE = re.compile(r"^[A-Za-z0-9]([A-Za-z0-9._-]{0,38}[A-Za-z0-9])?$") # "Miembro" rather than "Usuario" on the screens, while the stored value stays # `user`: renaming the value would mean a migration and rewriting every role # check for a word nobody types. -ROLE_LABELS = {"owner": "Responsable", "admin": "Administrador", - "moderator": "Moderador", "user": "Miembro"} +ROLE_LABELS = {"superadmin": "Superadministrador", "owner": "Responsable", + "admin": "Administrador", "moderator": "Moderador", + "user": "Miembro"} -# Who may be given which role on the Miembros screen, most trusted first, so -# the form and the predicates below cannot disagree about the list. -ASSIGNABLE_ROLES = ("admin", "moderator", "user") +# Who may be given which role, by whom. A function rather than the constant it +# used to be, because the answer now depends on who is asking: the role picker +# must never offer what the handler will refuse, and with two levels above admin +# a single list can only be right for one of them. +def assignable_roles(actor_role: str) -> tuple[str, ...]: + return tuple(role for role in ("admin", "moderator", "user") + if may_create(actor_role, role)) def may_create(actor_role: str, target_role: str) -> bool: - """Who may bring whom in. Admins cannot mint more admins.""" + """Who may bring whom in. + + **An admin account is the superadministrator's alone** — that is the line + this phase exists to draw. The responsable runs the association and can fill + it with members and moderators; who administers the platform is not theirs + to decide, which is what makes it safe to hand the responsable chair to a + customer organisation's president. + + Nobody creates a superadministrator or a responsable here. Both are single + chairs held by a unique index, and both change hands by transfer, below. + """ if target_role == "admin": - return actor_role == "owner" + return actor_role == "superadmin" if target_role in ("moderator", "user"): - return actor_role in ("owner", "admin") + return actor_role in ("superadmin", "owner", "admin") return False @@ -64,12 +83,20 @@ def may_manage(actor_role: str, target_role: str) -> bool: A moderator appears nowhere in this function, deliberately: they approve posts and nothing else. Being trusted to judge what the public reads is not the same as being trusted to suspend the person who wrote it. + + The two chairs are out of reach by the same rule that put them there. A + superadministrator cannot be suspended or demoted by anybody, themselves + included — the way out is to hand the platform on. The responsable is out of + reach of everyone below, and of the superadministrator too: the chair is the + association's, and a platform administrator quietly removing the president + of the organisation they host is exactly the move this separation exists to + make impossible. Transferring it is the association's own act. """ - if target_role == "owner": - return False # the owner is out of reach of everyone, themselves included + if target_role in ("superadmin", "owner"): + return False if target_role == "admin": - return actor_role == "owner" - return actor_role in ("owner", "admin") + return actor_role == "superadmin" + return actor_role in ("superadmin", "owner", "admin") def tombstone_id(db: sqlite3.Connection) -> int: @@ -77,17 +104,28 @@ def tombstone_id(db: sqlite3.Connection) -> int: return row["id"] -def transfer_ownership(db: sqlite3.Connection, owner_id: int, target_id: int) -> None: - """Hand ownership to an admin, atomically. +def transfer_ownership(db: sqlite3.Connection, holder_id: int, target_id: int, + chair: str) -> None: + """Hand one of the two chairs on, atomically. The demotion has to come first. With the partial unique index in place, a - promote-then-demote order would momentarily ask for two owners and the - database would refuse — correctly, but confusingly. + promote-then-demote order would momentarily ask for two holders of the chair + and the database would refuse — correctly, but confusingly. + + `chair` is 'superadmin' or 'owner' and comes from the route, never from a + request. The person giving it up becomes an admin, which is the most they + can be left with: there is no role above the one they just gave away. + + Filling an empty chair is the same call with nobody to demote — the first + UPDATE matches no row and the transaction is one statement shorter. """ + if chair not in ("superadmin", "owner"): + raise ValueError(f"not a chair: {chair!r}") db.execute("BEGIN IMMEDIATE") try: - db.execute("UPDATE members SET role = 'admin' WHERE id = ?", (owner_id,)) - db.execute("UPDATE members SET role = 'owner' WHERE id = ?", (target_id,)) + db.execute("UPDATE members SET role = 'admin' WHERE id = ? AND role = ?", + (holder_id, chair)) + db.execute("UPDATE members SET role = ? WHERE id = ?", (chair, target_id)) db.execute("COMMIT") except Exception: db.execute("ROLLBACK") @@ -319,7 +357,7 @@ def new(): if request.method == "GET": return render_template( "member_new.html", - can_make_admin=g.member["role"] == "owner", + can_make_admin=may_create(g.member["role"], "admin"), # Without mail the invitation cannot leave the building, so the # admin has to pass the link on by hand. Worth knowing before # filling the form rather than after. @@ -454,7 +492,7 @@ def set_role(member_id: int): """ target = _load(member_id) role = request.form.get("role", "") - if role not in ASSIGNABLE_ROLES: + if role not in assignable_roles(g.member["role"]): abort(403) if not may_manage(g.member["role"], target["role"]): abort(403) @@ -468,12 +506,34 @@ def set_role(member_id: int): @bp.route("/miembros//transferir", methods=["POST"]) @owner_required def transfer(member_id: int): + """Hand the association on. The responsable's own act, or the + superadministrator filling an empty chair.""" + target = _load(member_id) + if target["role"] not in ("admin", "moderator", "user") or not target["active"]: + flash("Solo puedes nombrar responsable a un miembro activo.", "error") + return redirect(_page(target)) + transfer_ownership(get_db(), g.member["id"], target["id"], "owner") + flash(f"{target['display_name']} es ahora el responsable.", "ok") + return redirect(_page(target)) + + +@bp.route("/miembros//transferir-plataforma", methods=["POST"]) +@superadmin_required +def transfer_platform(member_id: int): + """Hand the platform on. + + Separate from the route above because they are different jobs, and because + conflating them is how somebody hands away more than they meant to: this one + is irreversible from the giver's side — the moment it commits, the person + running it is an admin and cannot take it back. + """ target = _load(member_id) if target["role"] != "admin" or not target["active"]: - flash("Solo puedes transferir la titularidad a un administrador activo.", "error") + flash("Solo puedes entregar la plataforma a un administrador activo.", "error") return redirect(_page(target)) - transfer_ownership(get_db(), g.member["id"], target["id"]) - flash(f"{target['display_name']} es ahora el responsable. Tú eres administrador.", "ok") + transfer_ownership(get_db(), g.member["id"], target["id"], "superadmin") + flash(f"{target['display_name']} es ahora el superadministrador. " + "Tú eres administrador.", "ok") return redirect(_page(target)) @@ -481,7 +541,10 @@ def transfer(member_id: int): @owner_required def erase(member_id: int): target = _load(member_id) - if target["role"] == "owner": + # Through the predicate rather than a bare role test: the two chairs are + # unreachable by exactly the rule that protects them everywhere else, and a + # second spelling of it here is a second place to get it wrong. + if not may_manage(g.member["role"], target["role"]): abort(403) # Files only after the transaction has committed: a rollback can put the # rows back, and nothing can put the pictures back. diff --git a/apps/board/migrations.py b/apps/board/migrations.py index c2c8c03..c5709d4 100644 --- a/apps/board/migrations.py +++ b/apps/board/migrations.py @@ -249,6 +249,70 @@ def _no_more_categories(db: sqlite3.Connection) -> None: db.execute(f"ALTER TABLE {table} DROP COLUMN categories") +def _a_superadmin_above_the_owner(db: sqlite3.Connection) -> None: + """Add the `superadmin` role, and give it to whoever is the owner today. + + The same rebuild as step 4, for the same reason — `role` carries a CHECK and + SQLite has no DROP CONSTRAINT — so the notes there about the eight tables + that reference `members`, about the rename, and about foreign keys being off + outside the transaction all apply here unchanged. Two things are particular + to this step: + + * **Both partial unique indexes have to be created afterwards.** The copy + carries neither. Losing `members_one_owner` would quietly allow a second + responsable, and never creating `members_one_superadmin` would allow two + superadministrators — which is the one rule this whole phase rests on. + * **The existing owner is promoted.** Nobody has to type anything, nothing + is erased, and the person who could already do everything keeps being able + to. It leaves the responsable chair empty, which breaks nothing: a + superadministrator passes every check an owner passes, and the chair is + filled from inside the app whenever there is somebody to put in it. + """ + if "superadmin" in _role_check(db): + return + + db.execute(""" + CREATE TABLE members_new ( + id INTEGER PRIMARY KEY, + gitea_login TEXT NOT NULL UNIQUE COLLATE NOCASE, + display_name TEXT NOT NULL DEFAULT '', + email TEXT NOT NULL DEFAULT '', + password_hash TEXT, + profile_published INTEGER NOT NULL DEFAULT 0 CHECK (profile_published IN (0, 1)), + bio TEXT, + links TEXT, + photo_name TEXT, + role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', + 'moderator', 'user', 'tombstone')), + active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)), + created_at TEXT NOT NULL DEFAULT (datetime('now')), + created_by INTEGER REFERENCES members(id), + last_seen_at TEXT + )""") + db.execute(""" + INSERT INTO members_new + (id, gitea_login, display_name, email, password_hash, + profile_published, bio, links, photo_name, + role, active, created_at, created_by, last_seen_at) + SELECT id, gitea_login, display_name, email, password_hash, + profile_published, bio, links, photo_name, + role, active, created_at, created_by, last_seen_at + FROM members""") + db.execute("DROP TABLE members") + db.execute("ALTER TABLE members_new RENAME TO members") + # Promoted before the indexes exist, so the row is never momentarily both + # the only owner and the only superadmin under two rules at once. + db.execute("UPDATE members SET role = 'superadmin' WHERE role = 'owner'") + db.execute("""CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin + ON members(role) WHERE role = 'superadmin'""") + db.execute("""CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner + ON members(role) WHERE role = 'owner'""") + + broken = db.execute("PRAGMA foreign_key_check").fetchall() + if broken: + raise RuntimeError(f"migration left dangling references: {broken}") + + # (number, description, function). The number is the value written to # user_version once the step succeeds. STEPS = [ @@ -258,6 +322,7 @@ STEPS = [ (4, "members can be moderators", _members_can_moderate), (5, "events carry a date of their own", _rooms_for_a_date_of_its_own), (6, "there are no categories any more", _no_more_categories), + (7, "a superadministrator above the responsable", _a_superadmin_above_the_owner), ] diff --git a/apps/board/schema.sql b/apps/board/schema.sql index 9ad1ca4..15a3491 100644 --- a/apps/board/schema.sql +++ b/apps/board/schema.sql @@ -20,9 +20,10 @@ CREATE TABLE IF NOT EXISTS members ( bio TEXT, links TEXT, -- JSON array of {label, url} photo_name TEXT, - -- 'moderator' arrived with migration 4, which had to rebuild this table: - -- SQLite has no DROP CONSTRAINT, so widening a CHECK is never an ALTER. - role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator', + -- 'moderator' arrived with migration 4 and 'superadmin' with migration 7, + -- each of which had to rebuild this table: SQLite has no DROP CONSTRAINT, so + -- widening a CHECK is never an ALTER. + role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', 'moderator', 'user', 'tombstone')), active INTEGER NOT NULL DEFAULT 1 CHECK (active IN (0, 1)), created_at TEXT NOT NULL DEFAULT (datetime('now')), @@ -30,9 +31,17 @@ CREATE TABLE IF NOT EXISTS members ( last_seen_at TEXT ); --- The one-owner rule, held by the database rather than by the application, so --- a mistake in a handler cannot produce a second owner. SQLite enforces a --- partial unique index exactly like a full one. +-- Two chairs, one person each, held by the database rather than by the +-- application, so a mistake in a handler cannot produce a second of either. +-- SQLite enforces a partial unique index exactly like a full one. +-- The superadministrator runs the platform — admin accounts, the look +-- and the identity — and the responsable runs the association — the members, +-- the moderators and the invitations. Installed for a second organisation, the +-- first is whoever maintains the box and the second is their president, which +-- is the whole reason the two are separate rows rather than one. +CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin + ON members(role) WHERE role = 'superadmin'; + CREATE UNIQUE INDEX IF NOT EXISTS members_one_owner ON members(role) WHERE role = 'owner'; diff --git a/apps/board/security.py b/apps/board/security.py index 296cf0c..3a761ab 100644 --- a/apps/board/security.py +++ b/apps/board/security.py @@ -43,12 +43,38 @@ def login_required(view): return wrapped +# Most trusted first. Every decorator below is "this role or anything above it", +# which is the one rule worth keeping in a list rather than in four functions: +# adding a tier then means adding a word here, not auditing every check. +LADDER = ("superadmin", "owner", "admin", "moderator", "user") + + +def _at_least(rank: str): + """The roles that pass a check for `rank` — it and everything above it.""" + return LADDER[:LADDER.index(rank) + 1] + + +def is_at_least(role: str, rank: str) -> bool: + """`role` is `rank` or anything above it. + + Exported because seven places outside this module had the same question + written as a literal tuple — `g.member["role"] in ("owner", "admin")` — and + every one of them silently excluded the superadministrator the moment a tier + was added above owner. A tuple is a copy of a rule; this is the rule. + """ + return role in _at_least(rank) + + def admin_required(view): - """Owner counts as an admin. Admin does not count as owner.""" + """The superadministrator and the responsable both count as admins. + + Not the other way round: an admin is not a responsable, and neither is a + responsable the superadministrator. + """ @wraps(view) @login_required def wrapped(*args, **kwargs): - if g.member["role"] not in ("owner", "admin"): + if g.member["role"] not in _at_least("admin"): abort(403) return view(*args, **kwargs) return wrapped @@ -65,17 +91,39 @@ def moderator_required(view): @wraps(view) @login_required def wrapped(*args, **kwargs): - if g.member["role"] not in ("owner", "admin", "moderator"): + if g.member["role"] not in _at_least("moderator"): abort(403) return view(*args, **kwargs) return wrapped def owner_required(view): + """The association's chair. The superadministrator passes it too. + + Everything the responsable may do, the superadministrator may do; the + reverse is the whole point of there being two roles, and is + `superadmin_required` below. + """ @wraps(view) @login_required def wrapped(*args, **kwargs): - if g.member["role"] != "owner": + if g.member["role"] not in _at_least("owner"): + abort(403) + return view(*args, **kwargs) + return wrapped + + +def superadmin_required(view): + """The platform: admin accounts, the look, the identity, the system tools. + + The only check with nothing above it. A responsable who wants one of these + screens is a responsable who should be asking the person who installed this, + which is exactly the line the two roles are drawn along. + """ + @wraps(view) + @login_required + def wrapped(*args, **kwargs): + if g.member["role"] != "superadmin": abort(403) return view(*args, **kwargs) return wrapped diff --git a/apps/board/submissions.py b/apps/board/submissions.py index e0ffda5..af5d512 100644 --- a/apps/board/submissions.py +++ b/apps/board/submissions.py @@ -33,7 +33,7 @@ from flask import (Blueprint, abort, current_app, flash, g, redirect, from . import content, gitea, uploads from .db import get_db from .render import excerpt, to_html -from .security import login_required, moderator_required +from .security import is_at_least, login_required, moderator_required bp = Blueprint("submissions", __name__) @@ -54,7 +54,7 @@ STATE_LABELS = { def may_moderate(member=None) -> bool: member = member or g.member - return member is not None and member["role"] in ("owner", "admin", "moderator") + return member is not None and is_at_least(member["role"], "moderator") def pending_count() -> int: diff --git a/apps/board/templates/gestion.html b/apps/board/templates/gestion.html index ffb4a41..ad7a866 100644 --- a/apps/board/templates/gestion.html +++ b/apps/board/templates/gestion.html @@ -53,6 +53,7 @@

+{% if g.member.role == 'superadmin' %}

Marca

@@ -67,6 +68,7 @@ volver a lo de fábrica.

+{% endif %} {% if counts.pending %}
diff --git a/apps/board/templates/member.html b/apps/board/templates/member.html index 3c67fa7..b5b28af 100644 --- a/apps/board/templates/member.html +++ b/apps/board/templates/member.html @@ -14,8 +14,13 @@ {% block title %}{{ member.display_name }}{% endblock %} {% set me = g.member %} -{% set is_owner = me.role == 'owner' %} -{% set is_admin = me.role in ('owner', 'admin') %} +{# The template mirrors the predicates in members.py rather than restating + them: `can_assign` is the same list the handler will accept, so the picker + cannot offer a role that comes back 403. #} +{% set is_super = me.role == 'superadmin' %} +{% set is_chair = me.role in ('superadmin', 'owner') %} +{% set is_admin = me.role in ('superadmin', 'owner', 'admin') %} +{% set can_assign = assignable_roles(me.role) %} {% block main %}
@@ -139,7 +144,7 @@ {% endif %} {% endif %} -{% if is_admin and member.role != 'owner' and not is_me %} +{% if is_admin and member.role not in ('superadmin', 'owner') and not is_me %} {# Moved here from the directory cards. A
, not a script: the CSP has no 'unsafe-inline'. Every button is still checked in its handler — this block being hidden from a moderator is a courtesy, not the rule. #} @@ -164,36 +169,48 @@ {% endif %} - {% if is_owner or member.role != 'admin' %} + {% if member.role in can_assign or member.role not in ('admin',) %}
{% endif %} - {% if is_owner %} - {% if member.role == 'admin' and member.active %} -
- - -
- {% endif %} + {% if is_chair and member.active %} + {# Naming the responsable: the association's chair. The superadministrator + can fill it when it is empty — a fresh install has nobody in it — and + the responsable can hand it on. #} +
+ + +
+ {% endif %} -
- - -
+ {% if is_super and member.role == 'admin' and member.active %} + {# Handing the platform on. Its own button, and its own sentence, because + it is irreversible from this side: the moment it commits you are an + administrator and cannot take it back. #} +
+ + +
+ {% endif %} + + {% if is_chair %} +
+ + +
{% endif %} {% if member.email %}

{{ member.email }}

{% endif %} diff --git a/apps/board/templates/members.html b/apps/board/templates/members.html index 884cc84..4a90610 100644 --- a/apps/board/templates/members.html +++ b/apps/board/templates/members.html @@ -64,10 +64,11 @@ {% if is_admin %}

- Hay un solo responsable. El responsable da de alta administradores; los - administradores dan de alta miembros y moderadores. Suspender, cambiar el rol, - reenviar la invitación y eliminar están en la ficha de cada persona, bajo - «Gestionar». + Hay un solo superadministrador y un solo responsable. El superadministrador + lleva la plataforma: las cuentas de administrador, el aspecto y la identidad + del sitio. El responsable lleva la asociación: los miembros, los moderadores + y las invitaciones. Suspender, cambiar el rol, reenviar la invitación y + eliminar están en la ficha de cada persona, bajo «Gestionar».

{% endif %} {% endblock %} diff --git a/apps/board/tests/conftest.py b/apps/board/tests/conftest.py index 523d893..e049071 100644 --- a/apps/board/tests/conftest.py +++ b/apps/board/tests/conftest.py @@ -65,9 +65,23 @@ def make_member(db): return _make +@pytest.fixture +def superadmin_id(db): + """The account BOARD_OWNER seeds: the superadministrator, who runs the + platform and passes every check below them.""" + return db.execute( + "SELECT id FROM members WHERE role = 'superadmin'").fetchone()["id"] + + @pytest.fixture def owner_id(db): - return db.execute("SELECT id FROM members WHERE role = 'owner'").fetchone()["id"] + """A responsable — the association's chair, which is empty on a fresh + install. Minted here because the two roles are deliberately different + people, and a test that means one should not reach for the other.""" + return db.execute( + """INSERT INTO members (gitea_login, display_name, email, role) + VALUES ('presidenta', 'Presidenta', 'presidenta@example.com', 'owner')""" + ).lastrowid @pytest.fixture diff --git a/apps/board/tests/test_brand.py b/apps/board/tests/test_brand.py index e401a88..127fe14 100644 --- a/apps/board/tests/test_brand.py +++ b/apps/board/tests/test_brand.py @@ -99,10 +99,12 @@ def test_an_unreadable_pair_warns_and_a_readable_one_does_not(): # --- the form ------------------------------------------------------------- @pytest.fixture -def admin(make_member, sign_in): - member_id = make_member("admina", role="admin") - sign_in(member_id) - return member_id +def admin(superadmin_id, sign_in): + """The superadministrator. Named `admin` because every test below reads + "signed in as the person who may change this", and that person is no longer + an administrator: the look and the identity are the platform's.""" + sign_in(superadmin_id) + return superadmin_id # Arguments for the test client rather than fields of the form. Separated by @@ -125,8 +127,11 @@ def save(post, **fields): return post("/comunidad/gestion/marca", data, **sent) -def test_only_admins_reach_it(client, post, make_member, sign_in): - for role in ("user", "moderator"): +def test_only_the_superadmin_reaches_it(client, post, make_member, sign_in): + """An administrator is refused too, which is the change: the colours and the + identity belong to whoever runs the platform, not to the association's + committee.""" + for role in ("user", "moderator", "admin", "owner"): sign_in(make_member(f"persona-{role}", role=role)) assert client.get("/comunidad/gestion/marca").status_code == 403 assert save(post, **{"token-brand": "#1b5e20"}).status_code == 403 @@ -370,17 +375,20 @@ def test_restoring_empties_the_row_and_the_disk(app, client, db, post, admin): # --- erasure -------------------------------------------------------------- -def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id, - make_member, sign_in): +def test_erasing_whoever_set_the_brand_leaves_it_standing(client, db, post, admin, + make_member): """The colours belong to the association, like an event in the calendar. - An admin leaving is not a reason for the site to look like a default - install again.""" - admin_id = make_member("admina", role="admin") - sign_in(admin_id) - save(post, **{"token-brand": "#1b5e20"}) + Whoever set them leaving is not a reason for the site to look like a default + install again. - sign_in(owner_id) - post(f"/comunidad/miembros/{admin_id}/eliminar") + The row erased is a former superadministrator who has since handed the + platform on and is an admin again — which is the only way a row that set the + brand can become erasable at all, since neither chair can be erased.""" + former = make_member("anterior", role="admin") + save(post, **{"token-brand": "#1b5e20"}) + db.execute("UPDATE brand SET updated_by = ? WHERE id = 1", (former,)) + + post(f"/comunidad/miembros/{former}/eliminar") row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone() assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"} diff --git a/apps/board/tests/test_events.py b/apps/board/tests/test_events.py index 686158e..b253b69 100644 --- a/apps/board/tests/test_events.py +++ b/apps/board/tests/test_events.py @@ -24,9 +24,9 @@ def quiet_gitea(monkeypatch): @pytest.fixture -def an_event(post, owner_id, sign_in, quiet_gitea): +def an_event(post, superadmin_id, sign_in, quiet_gitea): def _add(title="Asamblea", starts_on="2026-10-24", **extra): - sign_in(owner_id) + sign_in(superadmin_id) data = {"title": title, "starts_on": starts_on} data.update(extra) post("/comunidad/calendario/nuevo", data) @@ -72,19 +72,19 @@ def test_the_calendar_itself_is_behind_the_login(client): # --- the month ----------------------------------------------------------- def test_the_month_shows_its_own_events_and_not_the_neighbours( - client, an_event, owner_id, sign_in): + client, an_event, superadmin_id, sign_in): an_event("Asamblea", "2026-10-24") an_event("Ensayo", "2026-11-03") - sign_in(owner_id) + sign_in(superadmin_id) october = client.get("/comunidad/calendario?mes=2026-10").get_data(as_text=True) assert "Asamblea" in october assert "Ensayo" not in october -def test_the_arrows_cross_the_year(client, an_event, owner_id, sign_in): - sign_in(owner_id) +def test_the_arrows_cross_the_year(client, an_event, superadmin_id, sign_in): + sign_in(superadmin_id) page = client.get("/comunidad/calendario?mes=2026-12").get_data(as_text=True) assert "mes=2027-01" in page @@ -98,10 +98,10 @@ def test_shifting_months_wraps_properly(): def test_a_mistyped_month_shows_today_rather_than_an_error( - client, owner_id, sign_in, quiet_gitea): + client, superadmin_id, sign_in, quiet_gitea): """A calendar that refuses to draw because a query string was mistyped is worse than one that shows now.""" - sign_in(owner_id) + sign_in(superadmin_id) today = date.today() page = client.get("/comunidad/calendario?mes=pumpkin") @@ -110,8 +110,8 @@ def test_a_mistyped_month_shows_today_rather_than_an_error( assert events.month_label(today.year, today.month) in page.get_data(as_text=True) -def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, quiet_gitea): - sign_in(owner_id) +def test_february_in_a_leap_year_has_twenty_nine_days(client, superadmin_id, sign_in, quiet_gitea): + sign_in(superadmin_id) page = client.get("/comunidad/calendario?mes=2028-02").get_data(as_text=True) assert ">29<" in page assert ">30<" not in page @@ -120,13 +120,13 @@ def test_february_in_a_leap_year_has_twenty_nine_days(client, owner_id, sign_in, # --- what the git server does to this ------------------------------------ def test_the_private_events_survive_a_git_server_that_is_down( - client, post, owner_id, sign_in, monkeypatch): + client, post, superadmin_id, sign_in, monkeypatch): """The half that only exists here must not be taken down by the half that does not. A refused connection reaches this module as a GiteaError because gitea.py translates it — before that it was a bare OSError and this page would have 500ed.""" import requests - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) def refuse(*args, **kwargs): @@ -143,10 +143,10 @@ def test_the_private_events_survive_a_git_server_that_is_down( # --- the .ics ------------------------------------------------------------- -def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, sign_in): +def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, superadmin_id, sign_in): an_event("Asamblea", "2026-10-24", starts_at="19:00", location="Local de la asociación") - sign_in(owner_id) + sign_in(superadmin_id) response = client.get("/comunidad/calendario/1.ics") @@ -159,22 +159,22 @@ def test_the_ics_is_a_calendar_a_phone_understands(client, an_event, owner_id, s assert "UID:evento-1@vienalatina.com" in body # stable, so re-adding updates -def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, owner_id, sign_in): +def test_an_event_with_no_time_lasts_the_whole_day(client, an_event, superadmin_id, sign_in): """VALUE=DATE rather than inventing midnight, which is how a calendar shows it as a band across the top of the day.""" an_event("Jornada", "2026-10-24") - sign_in(owner_id) + sign_in(superadmin_id) body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True) assert "DTSTART;VALUE=DATE:20261024" in body -def test_a_comma_in_the_place_is_escaped(client, an_event, owner_id, sign_in): +def test_a_comma_in_the_place_is_escaped(client, an_event, superadmin_id, sign_in): """An unescaped comma in LOCATION makes the rest of the line a second value, and the address arrives truncated.""" an_event("Asamblea", "2026-10-24", location="Plaza de Ottakring, junto al mercado") - sign_in(owner_id) + sign_in(superadmin_id) body = client.get("/comunidad/calendario/1.ics").get_data(as_text=True) @@ -196,8 +196,8 @@ def test_the_ics_needs_a_session(client, an_event): # --- refusals ------------------------------------------------------------- -def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): - sign_in(owner_id) +def test_an_event_without_a_date_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea): + sign_in(superadmin_id) response = post("/comunidad/calendario/nuevo", {"title": "Algún día"}) @@ -205,8 +205,8 @@ def test_an_event_without_a_date_is_refused(client, db, post, owner_id, sign_in, assert db.execute("SELECT COUNT(*) AS n FROM events").fetchone()["n"] == 0 -def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_gitea): - sign_in(owner_id) +def test_a_nonsense_time_is_refused(client, db, post, superadmin_id, sign_in, quiet_gitea): + sign_in(superadmin_id) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24", "starts_at": "25:99"}) @@ -217,14 +217,14 @@ def test_a_nonsense_time_is_refused(client, db, post, owner_id, sign_in, quiet_g # --- erasure -------------------------------------------------------------- def test_erasing_the_admin_leaves_the_event_standing( - db, post, an_event, owner_id, make_member, sign_in, quiet_gitea): + db, post, an_event, superadmin_id, make_member, sign_in, quiet_gitea): """The meeting still happens after they leave: the event belongs to the association, so the row stays and the name goes.""" admin = make_member("admina", role="admin") sign_in(admin) post("/comunidad/calendario/nuevo", {"title": "Asamblea", "starts_on": "2026-10-24"}) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{admin}/eliminar") row = db.execute("SELECT title, created_by FROM events").fetchone() diff --git a/apps/board/tests/test_invites.py b/apps/board/tests/test_invites.py index fd888b8..4ba2fdf 100644 --- a/apps/board/tests/test_invites.py +++ b/apps/board/tests/test_invites.py @@ -222,10 +222,10 @@ def test_a_suspended_member_gets_no_reset(client, post, make_member, outbox): # --- inviting from the members screen ------------------------------------- def test_creating_a_member_emails_them_instead_of_showing_a_password( - app, client, post, owner_id, sign_in, outbox, monkeypatch): + app, client, post, superadmin_id, sign_in, outbox, monkeypatch): monkeypatch.setattr(gitea, "admin_create_user", lambda login, email, name, password: None) - sign_in(owner_id) + sign_in(superadmin_id) response = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -241,7 +241,7 @@ def test_creating_a_member_emails_them_instead_of_showing_a_password( def test_when_mail_fails_the_admin_is_given_the_link( - app, client, post, owner_id, sign_in, monkeypatch): + app, client, post, superadmin_id, sign_in, monkeypatch): """Otherwise the account exists and the member simply never gets in.""" monkeypatch.setattr(gitea, "admin_create_user", lambda login, email, name, password: None) @@ -249,7 +249,7 @@ def test_when_mail_fails_the_admin_is_given_the_link( def explode(to, subject, body): raise mail.MailFailed("connection refused") monkeypatch.setattr(mail, "send", explode) - sign_in(owner_id) + sign_in(superadmin_id) response = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -265,13 +265,13 @@ def test_when_mail_fails_the_admin_is_given_the_link( # --- when the server cannot send at all ----------------------------------- def test_an_unconfigured_server_does_not_blame_the_mail_server( - app, client, post, owner_id, sign_in, monkeypatch): + app, client, post, superadmin_id, sign_in, monkeypatch): """No MAIL_HOST is not a failure, and saying "no se pudo enviar" sends the admin hunting for an SMTP error that was never produced.""" monkeypatch.setattr(gitea, "admin_create_user", lambda login, email, name, password: None) app.config["MAIL_HOST"] = "" - sign_in(owner_id) + sign_in(superadmin_id) page = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -283,9 +283,9 @@ def test_an_unconfigured_server_does_not_blame_the_mail_server( assert "/comunidad/invitacion/" in page -def test_the_form_warns_before_it_is_filled_in(app, client, owner_id, sign_in): +def test_the_form_warns_before_it_is_filled_in(app, client, superadmin_id, sign_in): app.config["MAIL_HOST"] = "" - sign_in(owner_id) + sign_in(superadmin_id) assert "no envía correo" in client.get( "/comunidad/miembros/nuevo").get_data(as_text=True) @@ -323,13 +323,13 @@ def test_recovery_is_always_offered_now(app, client): # member added any other way had no route in at all: no invitation was ever # issued for them and nothing could issue one later. -def test_an_existing_member_can_be_invited(app, client, post, owner_id, make_member, +def test_an_existing_member_can_be_invited(app, client, post, superadmin_id, make_member, sign_in, outbox): """The case that prompted this: the admin made the account by hand, added the member with the box unticked, and nobody could reach the account — including the admin, who never knew the password.""" member_id = make_member("salvador") - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/invitar") @@ -339,12 +339,12 @@ def test_an_existing_member_can_be_invited(app, client, post, owner_id, make_mem assert invites.lookup(token_in(outbox[0]["body"])) is not None -def test_re_inviting_kills_the_previous_link(app, client, post, owner_id, make_member, +def test_re_inviting_kills_the_previous_link(app, client, post, superadmin_id, make_member, sign_in, outbox): """A link that was forwarded, or is sitting in a mailbox somebody else can read, must stop working the moment a replacement is sent.""" member_id = make_member("salvador") - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/invitar") post(f"/comunidad/miembros/{member_id}/invitar") @@ -370,13 +370,13 @@ def test_a_plain_user_cannot_invite(client, post, make_member, sign_in, outbox): def test_a_member_with_no_address_is_refused_before_a_token_is_made( - app, client, db, post, owner_id, sign_in, outbox): + app, client, db, post, superadmin_id, sign_in, outbox): """Issuing the token first would invalidate a previous, working invitation in exchange for one that cannot be delivered.""" member_id = db.execute( "INSERT INTO members (gitea_login, display_name, role) VALUES ('sincorreo', 'Sin', 'user')" ).lastrowid - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/invitar", follow_redirects=True) @@ -384,9 +384,9 @@ def test_a_member_with_no_address_is_refused_before_a_token_is_made( assert db.execute("SELECT 1 FROM invites").fetchone() is None -def test_a_suspended_member_cannot_be_invited(client, post, owner_id, make_member, +def test_a_suspended_member_cannot_be_invited(client, post, superadmin_id, make_member, sign_in, outbox): - sign_in(owner_id) + sign_in(superadmin_id) response = post(f"/comunidad/miembros/{make_member('fuera', active=0)}/invitar") assert response.status_code == 403 @@ -394,11 +394,11 @@ def test_a_suspended_member_cannot_be_invited(client, post, owner_id, make_membe def test_when_the_mail_fails_the_admin_is_handed_the_link( - app, client, post, owner_id, make_member, sign_in, monkeypatch): + app, client, post, superadmin_id, make_member, sign_in, monkeypatch): def explode(to, subject, body): raise mail.MailFailed("connection refused") monkeypatch.setattr(mail, "send", explode) - sign_in(owner_id) + sign_in(superadmin_id) page = post(f"/comunidad/miembros/{make_member('salvador')}/invitar", follow_redirects=True).get_data(as_text=True) diff --git a/apps/board/tests/test_members.py b/apps/board/tests/test_members.py index 1bb4c2f..8f635d6 100644 --- a/apps/board/tests/test_members.py +++ b/apps/board/tests/test_members.py @@ -11,31 +11,53 @@ from apps.board.members import may_create, may_manage # --- the rules as plain functions --------------------------------------- -def test_only_the_owner_makes_admins(): - assert may_create("owner", "admin") +def test_only_the_superadmin_makes_admins(): + """The line this phase draws. An admin account is the platform's, not the + association's — which is what makes it safe to hand the responsable chair to + a customer organisation's president.""" + assert may_create("superadmin", "admin") + assert not may_create("owner", "admin") assert not may_create("admin", "admin") assert not may_create("user", "admin") -def test_admins_and_the_owner_make_users(): +def test_everyone_above_a_moderator_makes_users(): + assert may_create("superadmin", "user") assert may_create("owner", "user") assert may_create("admin", "user") assert not may_create("user", "user") -def test_the_owner_is_beyond_everyone_including_themselves(): - assert not may_manage("owner", "owner") - assert not may_manage("admin", "owner") +def test_neither_chair_can_be_touched_by_anybody(): + """Both single chairs, both unreachable, for different reasons. The + superadministrator because there is nothing above them; the responsable + because the chair belongs to the association, and a platform administrator + quietly removing the president of the organisation they host is the move the + separation exists to prevent.""" + for actor in ("superadmin", "owner", "admin", "moderator", "user"): + assert not may_manage(actor, "superadmin"), actor + assert not may_manage(actor, "owner"), actor -def test_only_the_owner_manages_admins(): - assert may_manage("owner", "admin") +def test_only_the_superadmin_manages_admins(): + assert may_manage("superadmin", "admin") + assert not may_manage("owner", "admin") assert not may_manage("admin", "admin") +def test_the_role_picker_offers_exactly_what_the_handler_allows(): + """They used to be one constant and one predicate, which could only agree + for one actor once there were two levels above admin.""" + from apps.board.members import assignable_roles + for actor in ("superadmin", "owner", "admin", "moderator", "user"): + for role in ("admin", "moderator", "user"): + assert (role in assignable_roles(actor)) == may_create(actor, role), (actor, role) + + # --- the moderator, who curates content and not people ------------------- -def test_admins_and_the_owner_make_moderators(): +def test_admins_and_the_chairs_make_moderators(): + assert may_create("superadmin", "moderator") assert may_create("owner", "moderator") assert may_create("admin", "moderator") assert not may_create("moderator", "moderator") @@ -46,7 +68,7 @@ def test_a_moderator_has_no_power_over_anybody(): """The line the whole role rests on. Being trusted to judge what the public reads is not being trusted to suspend the person who wrote it, and a moderator who could do both would be a second kind of admin.""" - for target in ("owner", "admin", "moderator", "user"): + for target in ("superadmin", "owner", "admin", "moderator", "user"): assert not may_manage("moderator", target), target assert not may_create("moderator", target), target @@ -64,9 +86,8 @@ def test_an_admin_may_promote_a_member_to_moderator(client, db, post, make_membe def test_an_admin_still_cannot_mint_an_admin_through_the_role_form( client, db, post, make_member, sign_in): - """`set_role` moved from owner-only to admin-level so moderators can be - appointed routinely. That must not quietly hand admins the one power the - owner keeps.""" + """`set_role` is admin-level so moderators can be appointed routinely. That + must not quietly hand admins the one power the superadministrator keeps.""" admin = make_member("admina", role="admin") maria = make_member("maria") sign_in(admin) @@ -84,10 +105,10 @@ def test_a_moderator_cannot_change_a_role_at_all(client, db, post, make_member, def test_the_role_form_refuses_a_role_that_is_not_offered( - client, db, post, owner_id, make_member, sign_in): + client, db, post, superadmin_id, make_member, sign_in): """`tombstone` is a real value in the CHECK constraint and would make the member vanish from every listing while keeping their row.""" - sign_in(owner_id) + sign_in(superadmin_id) maria = make_member("maria") assert post(f"/comunidad/miembros/{maria}/rol", {"role": "tombstone"}).status_code == 403 @@ -96,24 +117,44 @@ def test_the_role_form_refuses_a_role_that_is_not_offered( # --- the database holds the line ---------------------------------------- -def test_a_second_owner_is_impossible(db): +def test_a_second_superadmin_is_impossible(db, superadmin_id): """Not a route check — a direct insert, because the point of the partial unique index is to survive a bug in the code above it.""" with pytest.raises(sqlite3.IntegrityError): db.execute( - "INSERT INTO members (gitea_login, role) VALUES ('usurpador', 'owner')" + "INSERT INTO members (gitea_login, role) VALUES ('usurpador', 'superadmin')" ) -def test_transfer_leaves_exactly_one_owner(app, db, owner_id, make_member): - from apps.board.members import transfer_ownership - admin_id = make_member("segunda", role="admin") - transfer_ownership(db, owner_id, admin_id) +def test_a_second_owner_is_impossible(db, owner_id): + with pytest.raises(sqlite3.IntegrityError): + db.execute( + "INSERT INTO members (gitea_login, role) VALUES ('usurpadora', 'owner')" + ) - owners = db.execute("SELECT id FROM members WHERE role = 'owner'").fetchall() - assert [row["id"] for row in owners] == [admin_id] + +@pytest.mark.parametrize("chair", ["superadmin", "owner"]) +def test_transfer_leaves_exactly_one_holder(app, db, superadmin_id, make_member, chair): + """Both chairs hand on the same way. The demotion comes first, or the unique + index refuses the promotion halfway through.""" + from apps.board.members import transfer_ownership + holder = superadmin_id if chair == "superadmin" else make_member("presi", role="owner") + admin_id = make_member("segunda", role="admin") + + transfer_ownership(db, holder, admin_id, chair) + + holders = db.execute("SELECT id FROM members WHERE role = ?", (chair,)).fetchall() + assert [row["id"] for row in holders] == [admin_id] assert db.execute("SELECT role FROM members WHERE id = ?", - (owner_id,)).fetchone()["role"] == "admin" + (holder,)).fetchone()["role"] == "admin" + + +def test_a_transfer_to_something_that_is_not_a_chair_is_refused(db, superadmin_id, make_member): + """`chair` comes from the route and never from a request, and this is what + keeps that true if somebody ever wires it to one.""" + from apps.board.members import transfer_ownership + with pytest.raises(ValueError): + transfer_ownership(db, superadmin_id, make_member("otra"), "admin") # --- the routes ---------------------------------------------------------- @@ -127,8 +168,8 @@ def test_admin_cannot_create_an_admin(client, post, make_member, sign_in): assert response.status_code == 403 -def test_owner_can_create_an_admin(client, db, post, owner_id, sign_in): - sign_in(owner_id) +def test_the_superadmin_can_create_an_admin(client, db, post, superadmin_id, sign_in): + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": "nueva", "display_name": "Nueva", "email": "n@example.com", "role": "admin", @@ -142,15 +183,15 @@ def test_a_plain_user_cannot_reach_the_admin_screens(client, make_member, sign_i assert client.get("/comunidad/miembros/nuevo").status_code == 403 -def test_the_owner_cannot_be_suspended(client, post, owner_id, make_member, sign_in): +def test_the_superadmin_cannot_be_suspended(client, post, superadmin_id, make_member, sign_in): sign_in(make_member("admina", role="admin")) - response = post(f"/comunidad/miembros/{owner_id}/estado", {"active": "0"}) + response = post(f"/comunidad/miembros/{superadmin_id}/estado", {"active": "0"}) assert response.status_code == 403 -def test_the_owner_cannot_suspend_themselves(client, post, owner_id, sign_in): - sign_in(owner_id) - response = post(f"/comunidad/miembros/{owner_id}/estado", {"active": "0"}) +def test_the_superadmin_cannot_suspend_themselves(client, post, superadmin_id, sign_in): + sign_in(superadmin_id) + response = post(f"/comunidad/miembros/{superadmin_id}/estado", {"active": "0"}) assert response.status_code == 403 @@ -165,11 +206,11 @@ def test_an_admin_cannot_demote_another_admin(client, post, make_member, sign_in -def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id, make_member, sign_in): +def test_erasing_a_member_keeps_their_threads_readable(app, db, post, superadmin_id, make_member, sign_in): author = make_member("saliente") db.execute("INSERT INTO threads (author_id, title, body_md) VALUES (?, 'Hola', 'Texto')", (author,)) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{author}/eliminar") assert db.execute("SELECT 1 FROM members WHERE id = ?", (author,)).fetchone() is None @@ -180,36 +221,52 @@ def test_erasing_a_member_keeps_their_threads_readable(app, db, post, owner_id, assert row["display_name"] == "Miembro eliminado" -def test_the_member_page_renders_for_each_role(client, db, owner_id, make_member, sign_in): - """Every role takes a different branch through member.html — the owner sees - transfer and erase, an admin sees suspend, a plain member sees neither — so - each one is rendered here rather than trusted. +def test_the_member_page_renders_for_each_role(client, db, superadmin_id, owner_id, + make_member, sign_in): + """Every role takes a different branch through member.html — the + superadministrator alone sees «Entregar la plataforma», both chairs see + «Eliminar», an admin sees «Suspender» and a plain member sees none of it — + so each one is rendered here rather than trusted. - These controls used to be on the cards in the directory and are on the - person's page now, which is what this looks at. The owner's branch needs an - admin to transfer to, so the page opened is the admin's. + The page opened is always somebody else's: nobody manages themselves, the + block is not drawn on your own page, and a test looking at it would pass for + the wrong reason. """ admin_id = make_member("admina", role="admin") + cases = [ + (superadmin_id, "admina", ["Entregar la plataforma", "Eliminar", "Suspender"]), + (owner_id, "admina", ["Eliminar", "Suspender"]), + (admin_id, "usuaria", ["Suspender"]), + (make_member("usuaria"), "admina", []), + ] + forbidden = {"Entregar la plataforma", "Eliminar", "Suspender"} - for member_id, expected in ((owner_id, "Transferir titularidad"), - (admin_id, "Suspender"), - (make_member("usuaria"), None)): + for member_id, who, expected in cases: sign_in(member_id) - # Never your own page: nobody manages themselves, so the block is not - # drawn there and the test would pass for the wrong reason. - who = "usuaria" if member_id == admin_id else "admina" body = client.get(f"/comunidad/miembro/{who}").get_data(as_text=True) assert who.title() in body - if expected: - assert expected in body - else: - assert "Transferir titularidad" not in body - assert "Suspender" not in body + for phrase in expected: + assert phrase in body, (member_id, phrase) + for phrase in forbidden - set(expected): + assert phrase not in body, (member_id, phrase) + + +def test_the_responsable_cannot_reach_an_admin_from_their_page( + client, owner_id, make_member, sign_in): + """The association's chair runs the association. An admin account is the + platform's, so the whole management block is absent from their page.""" + make_member("admina", role="admin") + sign_in(owner_id) + + body = client.get("/comunidad/miembro/admina").get_data(as_text=True) + + assert "Gestionar" in body # it is drawn — an admin is manageable… + assert "Administrador" not in body.split("Gestionar")[1] # …but not into or out of admin def test_the_new_member_form_hides_the_role_choice_from_admins( - client, owner_id, make_member, sign_in): - sign_in(owner_id) + client, superadmin_id, make_member, sign_in): + sign_in(superadmin_id) assert "Administrador" in client.get("/comunidad/miembros/nuevo").get_data(as_text=True) sign_in(make_member("admina", role="admin")) @@ -236,7 +293,7 @@ def test_the_export_is_only_your_own_writing(client, db, make_member, sign_in): # --- erasing somebody who has left traces -------------------------------- -def test_erasing_a_member_who_posted_a_picture(app, db, post, owner_id, make_member, sign_in): +def test_erasing_a_member_who_posted_a_picture(app, db, post, superadmin_id, make_member, sign_in): """This failed in production with a 500 the first time it was tried. `attachments.uploaded_by` is NOT NULL and does not cascade, so with a @@ -251,7 +308,7 @@ def test_erasing_a_member_who_posted_a_picture(app, db, post, owner_id, make_mem VALUES (1, 'foto-abc123abc123.jpg', 'foto.jpg', 'image/jpeg', 10, ?)""", (author,), ) - sign_in(owner_id) + sign_in(superadmin_id) response = post(f"/comunidad/miembros/{author}/eliminar") @@ -297,11 +354,11 @@ def test_every_table_pointing_at_members_is_accounted_for(db): # --- onboarding, now that there is only one account to make -------------- def test_a_new_member_has_no_password_until_they_choose_one( - client, db, post, owner_id, sign_in, monkeypatch): + client, db, post, superadmin_id, sign_in, monkeypatch): """No password is generated and none is shown. Until the invitation is used, password_hash is NULL — and a NULL hash cannot be signed in with.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "m@example.com", @@ -314,10 +371,10 @@ def test_a_new_member_has_no_password_until_they_choose_one( assert row["password_hash"] is None -def test_an_address_is_required(client, db, post, owner_id, sign_in): +def test_an_address_is_required(client, db, post, superadmin_id, sign_in): """It is the only way the invitation reaches anybody, so a member without one is a row that can never be used.""" - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "María", "email": "", "role": "user", }) @@ -325,12 +382,12 @@ def test_an_address_is_required(client, db, post, owner_id, sign_in): def test_a_duplicate_is_refused_before_anything_is_written( - client, db, post, owner_id, make_member, sign_in, monkeypatch): + client, db, post, superadmin_id, make_member, sign_in, monkeypatch): """The error that started this: "ya están en uso" for somebody who was not on the list. There is one list now, so the message and the screen agree.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) make_member("maria") - sign_in(owner_id) + sign_in(superadmin_id) response = post("/comunidad/miembros/nuevo", { "login": "maria", "display_name": "Otra", "email": "otra@example.com", @@ -344,11 +401,11 @@ def test_a_duplicate_is_refused_before_anything_is_written( def test_erasing_a_member_lets_the_name_be_used_again( - client, db, post, owner_id, make_member, sign_in, monkeypatch): + client, db, post, superadmin_id, make_member, sign_in, monkeypatch): """Deleting used to leave an account behind on the other server, so the name stayed taken somewhere invisible. With one store, gone means gone.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{make_member('salvador')}/eliminar") post("/comunidad/miembros/nuevo", { @@ -477,3 +534,105 @@ def test_a_moderator_gets_no_controls_either(client, make_member, sign_in): assert client.post(f"/comunidad/miembros/{maria}/estado", data={"csrf_token": "token-for-tests", "active": "0"} ).status_code == 403 + + +# --- the two chairs, from the routes -------------------------------------- + +def test_an_admin_cannot_make_promote_or_erase_another_admin( + client, db, post, make_member, sign_in): + """Four doors into the same power, checked at each one. A hidden button is a + courtesy; these are the rules.""" + other = make_member("otra", role="admin") + sign_in(make_member("admina", role="admin")) + + assert post("/comunidad/miembros/nuevo", { + "login": "tercera", "display_name": "Tercera", + "email": "t@example.com", "role": "admin"}).status_code == 403 + assert post(f"/comunidad/miembros/{other}/rol", {"role": "user"}).status_code == 403 + assert post(f"/comunidad/miembros/{other}/estado", {"active": "0"}).status_code == 403 + assert post(f"/comunidad/miembros/{other}/eliminar").status_code == 403 + assert db.execute("SELECT role, active FROM members WHERE id = ?", + (other,)).fetchone()["role"] == "admin" + + +def test_the_responsable_cannot_touch_an_admin_either( + client, db, post, owner_id, make_member, sign_in): + """The chair this phase exists to make safe to hand over. A customer + organisation's president runs their association and does not administer the + platform that hosts it.""" + admin_id = make_member("admina", role="admin") + sign_in(owner_id) + + assert post("/comunidad/miembros/nuevo", { + "login": "nueva", "display_name": "Nueva", + "email": "n@example.com", "role": "admin"}).status_code == 403 + assert post(f"/comunidad/miembros/{admin_id}/rol", {"role": "user"}).status_code == 403 + assert post(f"/comunidad/miembros/{admin_id}/estado", {"active": "0"}).status_code == 403 + + +def test_nobody_reaches_the_superadmin_through_a_route( + client, post, superadmin_id, owner_id, make_member, sign_in): + for actor in (owner_id, make_member("admina", role="admin"), superadmin_id): + sign_in(actor) + assert post(f"/comunidad/miembros/{superadmin_id}/estado", + {"active": "0"}).status_code == 403, actor + assert post(f"/comunidad/miembros/{superadmin_id}/rol", + {"role": "user"}).status_code == 403, actor + assert post(f"/comunidad/miembros/{superadmin_id}/eliminar").status_code == 403, actor + + +def test_the_superadmin_cannot_erase_the_responsable(client, post, superadmin_id, + owner_id, sign_in): + """Deliberate, and the less obvious half of the separation: a platform + administrator quietly removing the president of the organisation they host + is exactly what two chairs are for.""" + sign_in(superadmin_id) + assert post(f"/comunidad/miembros/{owner_id}/eliminar").status_code == 403 + + +def test_handing_the_platform_on_is_the_superadmins_alone( + client, db, post, superadmin_id, owner_id, make_member, sign_in): + admin_id = make_member("admina", role="admin") + + for actor in (owner_id, admin_id): + sign_in(actor) + assert post(f"/comunidad/miembros/{admin_id}/transferir-plataforma" + ).status_code == 403 + + sign_in(superadmin_id) + post(f"/comunidad/miembros/{admin_id}/transferir-plataforma") + + assert db.execute("SELECT role FROM members WHERE id = ?", + (admin_id,)).fetchone()["role"] == "superadmin" + assert db.execute("SELECT role FROM members WHERE id = ?", + (superadmin_id,)).fetchone()["role"] == "admin" + + +def test_the_platform_only_goes_to_an_active_admin(client, db, post, superadmin_id, + make_member, sign_in): + sign_in(superadmin_id) + maria = make_member("maria") + suspended = make_member("dormida", role="admin", active=0) + + post(f"/comunidad/miembros/{maria}/transferir-plataforma") + post(f"/comunidad/miembros/{suspended}/transferir-plataforma") + + assert db.execute("SELECT role FROM members WHERE id = ?", + (superadmin_id,)).fetchone()["role"] == "superadmin" + + +def test_the_superadmin_can_fill_an_empty_responsable_chair( + client, db, post, superadmin_id, make_member, sign_in): + """A fresh install has nobody in it — migration 7 promotes the owner and + leaves the chair open — so somebody has to be able to seat the first one.""" + maria = make_member("maria") + sign_in(superadmin_id) + + post(f"/comunidad/miembros/{maria}/transferir") + + assert db.execute("SELECT role FROM members WHERE id = ?", + (maria,)).fetchone()["role"] == "owner" + # And the superadministrator is still the superadministrator: filling a + # chair you do not sit in costs you nothing. + assert db.execute("SELECT role FROM members WHERE id = ?", + (superadmin_id,)).fetchone()["role"] == "superadmin" diff --git a/apps/board/tests/test_messages.py b/apps/board/tests/test_messages.py index afd644b..a303398 100644 --- a/apps/board/tests/test_messages.py +++ b/apps/board/tests/test_messages.py @@ -301,7 +301,7 @@ def test_an_empty_message_with_no_picture_is_refused(client, db, post, make_memb # --- erasure -------------------------------------------------------------- def test_erasing_a_member_takes_their_private_messages( - app, client, db, post, owner_id, make_member, sign_in): + app, client, db, post, superadmin_id, make_member, sign_in): """Unlike a thread, which survives its author as "Miembro eliminado". A two-party exchange has no remainder to preserve, and keeping half of somebody's erased correspondence is what erasure exists to prevent.""" @@ -311,7 +311,7 @@ def test_erasing_a_member_takes_their_private_messages( content_type="multipart/form-data") name = db.execute("SELECT stored_name FROM attachments").fetchone()["stored_name"] - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") for table in ("conversations", "conversation_members", "messages", "attachments"): @@ -320,14 +320,14 @@ def test_erasing_a_member_takes_their_private_messages( def test_erasing_a_member_removes_blocks_either_way( - client, db, post, owner_id, make_member, sign_in): + client, db, post, superadmin_id, make_member, sign_in): maria, jose = make_member("maria"), make_member("jose") sign_in(maria) post(f"/comunidad/privados/bloquear/{jose}") sign_in(jose) post(f"/comunidad/privados/bloquear/{maria}") - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") assert db.execute("SELECT COUNT(*) AS n FROM blocks").fetchone()["n"] == 0 diff --git a/apps/board/tests/test_migrations.py b/apps/board/tests/test_migrations.py index 0bf5d20..6306dd8 100644 --- a/apps/board/tests/test_migrations.py +++ b/apps/board/tests/test_migrations.py @@ -181,28 +181,52 @@ def test_a_moderator_is_accepted_afterwards(old_db): def test_every_member_column_survives_the_rebuild(old_db): - """Thirteen columns copied by name. A typo in that list is a member losing - their email address, or their password, or their public page.""" - before = old_db.execute( - "SELECT id, gitea_login, display_name, email, role, active, created_by " - "FROM members ORDER BY id").fetchall() + """Thirteen columns copied by name, twice over now — steps 4 and 7 each + rebuild this table. A typo in either list is a member losing their email + address, or their password, or their public page. + + `role` is compared separately because step 7 deliberately changes exactly + one of them: see the test below.""" + columns = "id, gitea_login, display_name, email, active, created_by" + before = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall() migrations.apply(old_db) - after = old_db.execute( - "SELECT id, gitea_login, display_name, email, role, active, created_by " - "FROM members ORDER BY id").fetchall() + after = old_db.execute(f"SELECT {columns} FROM members ORDER BY id").fetchall() assert [tuple(row) for row in after] == [tuple(row) for row in before] -def test_the_one_owner_rule_survives_the_rebuild(old_db): - """The partial unique index is not copied with the rows, so it has to be - recreated by hand. Without it the database silently stops being the thing - that guarantees one owner, and a bug in a handler becomes two owners.""" +def test_the_owner_becomes_the_superadmin(old_db): + """Step 7's one intended change to the data. The person who could already do + everything keeps being able to, nobody types anything, and the responsable + chair is left empty for the association to fill.""" + was_owner = old_db.execute( + "SELECT gitea_login FROM members WHERE role = 'owner'").fetchone()["gitea_login"] + migrations.apply(old_db) + + assert old_db.execute( + "SELECT role FROM members WHERE gitea_login = ?", (was_owner,) + ).fetchone()["role"] == "superadmin" + assert old_db.execute("SELECT COUNT(*) FROM members WHERE role = 'owner'" + ).fetchone()[0] == 0 + + +@pytest.mark.parametrize("chair", ["superadmin", "owner"]) +def test_both_single_chair_rules_survive_the_rebuild(old_db, chair): + """Neither partial unique index is copied with the rows, so both have to be + recreated by hand. Without them the database silently stops being the thing + that guarantees one of each, and a bug in a handler becomes two.""" + migrations.apply(old_db) + # The superadmin chair is already filled by the promotion; the responsable + # chair is empty, so it takes one insert to fill before the rule can bite. + if chair == "owner": + old_db.execute("INSERT INTO members (gitea_login, display_name, role) " + "VALUES ('primera', 'Primera', 'owner')") + with pytest.raises(sqlite3.IntegrityError): old_db.execute("INSERT INTO members (gitea_login, display_name, role) " - "VALUES ('otro', 'Otro', 'owner')") + f"VALUES ('otro', 'Otro', '{chair}')") def test_nothing_pointing_at_a_member_is_left_dangling(old_db): @@ -266,10 +290,13 @@ def test_the_app_starts_against_a_database_from_before_all_this(tmp_path): old_sql = old_sql.replace(" password_hash TEXT,\n", "") # …and predates the moderator role, so step 4 has a CHECK to widen here too. old_sql = old_sql.replace( - " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'moderator',\n" + " role TEXT NOT NULL CHECK (role IN ('superadmin', 'owner', 'admin', 'moderator',\n" " 'user', 'tombstone')),", " role TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'user', 'tombstone')),") assert "CHECK (role IN ('owner', 'admin', 'user', 'tombstone'))" in old_sql + old_sql = old_sql.replace( + "CREATE UNIQUE INDEX IF NOT EXISTS members_one_superadmin\n" + " ON members(role) WHERE role = 'superadmin';\n\n", "") old_sql += """ CREATE TABLE gitea_tokens ( member_id INTEGER PRIMARY KEY REFERENCES members(id) ON DELETE CASCADE, @@ -359,3 +386,57 @@ def test_step_six_drops_the_category_columns_and_keeps_the_rows(tmp_path): assert db.execute("PRAGMA user_version").fetchone()[0] == max( number for number, _, _ in migrations.STEPS) db.close() + + +def test_a_restart_does_not_demote_the_superadmin(tmp_path): + """The one that would have shipped silently. + + `_seed_superadmin` ends with `ON CONFLICT(gitea_login) DO UPDATE SET role = + …`. While owner was the top of the tree that line was right. Left as it was + after step 7, it would have matched BOARD_OWNER's login on every container + restart and set the role back to `owner` — a privilege *reduction* arriving + at no particular moment, caused by nothing anybody did, and leaving + `members_one_superadmin` free for somebody else to take the chair. + + Nothing about a single start-up catches that; it takes a second one. + """ + from apps.board.app import create_app + from apps.board.db import connect + + path = str(tmp_path / "board.db") + settings = {"SECRET_KEY": "x", "DB_PATH": path, "OWNER_LOGIN": "pablo", + "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True} + + create_app(settings) + create_app(settings) # the restart + create_app(settings) # and another, because containers do that + + db = connect(path) + rows = db.execute( + "SELECT gitea_login, role FROM members WHERE role IN ('superadmin', 'owner')" + ).fetchall() + assert [(r["gitea_login"], r["role"]) for r in rows] == [("pablo", "superadmin")] + db.close() + + +def test_a_second_superadmin_is_not_seeded_over_the_first(tmp_path): + """Changing BOARD_OWNER must not hand the platform to whoever can edit the + environment — a quieter escalation than it looks, since editing a compose + file draws far less attention than asking for access.""" + from apps.board.app import create_app + from apps.board.db import connect + + path = str(tmp_path / "board.db") + base = {"SECRET_KEY": "x", "DB_PATH": path, + "UPLOAD_DIR": str(tmp_path / "uploads"), "TESTING": True} + + create_app({**base, "OWNER_LOGIN": "pablo"}) + create_app({**base, "OWNER_LOGIN": "intruso"}) + + db = connect(path) + assert db.execute( + "SELECT gitea_login FROM members WHERE role = 'superadmin'" + ).fetchone()["gitea_login"] == "pablo" + assert db.execute( + "SELECT COUNT(*) FROM members WHERE gitea_login = 'intruso'").fetchone()[0] == 0 + db.close() diff --git a/apps/board/tests/test_profiles.py b/apps/board/tests/test_profiles.py index 76087fb..4614aa3 100644 --- a/apps/board/tests/test_profiles.py +++ b/apps/board/tests/test_profiles.py @@ -121,13 +121,13 @@ def test_the_bio_cannot_smuggle_html(client, published): @pytest.mark.parametrize("name", ["de", "pt-br", "categories", "admin", "comunidad", "robots", "DE"]) -def test_a_name_the_site_already_uses_is_refused(client, db, post, owner_id, +def test_a_name_the_site_already_uses_is_refused(client, db, post, superadmin_id, sign_in, name, monkeypatch): """Not because it would break the site — Caddy gives the static site every collision — but because their page would never load and nobody would know why.""" monkeypatch.setattr("apps.board.mail.send", lambda to, subject, body: None) - sign_in(owner_id) + sign_in(superadmin_id) post("/comunidad/miembros/nuevo", { "login": name, "display_name": "X", "email": "x@example.com", "role": "user", }) @@ -187,7 +187,7 @@ def test_a_board_picture_cannot_be_served_as_a_profile_photo( def test_erasing_a_member_takes_the_photo_off_disk( - app, client, db, post, owner_id, sign_in, published): + app, client, db, post, superadmin_id, sign_in, published): member_id = published() sign_in(member_id) post("/comunidad/mi-perfil", {"published": "on", "bio": "Hola", @@ -197,7 +197,7 @@ def test_erasing_a_member_takes_the_photo_off_disk( (member_id,)).fetchone()["photo_name"] assert (Path(app.config["UPLOAD_DIR"]) / name).exists() - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{member_id}/eliminar") assert not (Path(app.config["UPLOAD_DIR"]) / name).exists() @@ -264,7 +264,7 @@ def test_their_page_links_out_to_the_public_one_when_there_is_one( assert 'href="/maria"' in client.get("/comunidad/miembro/maria").get_data(as_text=True) -def test_an_erased_members_name_is_not_a_link(client, post, owner_id, +def test_an_erased_members_name_is_not_a_link(client, post, superadmin_id, make_member, sign_in): """The one name with no page behind it. An erased member's writing is reassigned to the tombstone, which is not a person and has nothing to @@ -274,7 +274,7 @@ def test_an_erased_members_name_is_not_a_link(client, post, owner_id, sign_in(maria) post("/comunidad/nuevo", {"title": "Hola", "body": "Qué tal"}) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") body = client.get("/comunidad/muro").get_data(as_text=True) diff --git a/apps/board/tests/test_reactions.py b/apps/board/tests/test_reactions.py index 81b5491..f1a49ba 100644 --- a/apps/board/tests/test_reactions.py +++ b/apps/board/tests/test_reactions.py @@ -101,8 +101,8 @@ def test_the_count_and_my_own_mark_show_on_the_page(client, post, thread, def test_reacting_to_something_that_is_gone_is_a_404(db, post, thread, - owner_id, make_member, sign_in): - sign_in(owner_id) + superadmin_id, make_member, sign_in): + sign_in(superadmin_id) post(f"/comunidad/tema/{thread}/eliminar") sign_in(make_member("maria")) @@ -138,13 +138,13 @@ def test_the_button_comes_back_to_the_comment_it_was_pressed_on( assert response.headers["Location"].endswith(f"/comunidad/tema/{thread}#c1") -def test_erasing_a_member_takes_their_reactions(db, post, thread, owner_id, +def test_erasing_a_member_takes_their_reactions(db, post, thread, superadmin_id, make_member, sign_in): maria = make_member("maria") sign_in(maria) react(post, "thread", thread) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") assert db.execute("SELECT COUNT(*) AS n FROM reactions").fetchone()["n"] == 0 diff --git a/apps/board/tests/test_submissions.py b/apps/board/tests/test_submissions.py index f24a8fb..5518258 100644 --- a/apps/board/tests/test_submissions.py +++ b/apps/board/tests/test_submissions.py @@ -364,7 +364,7 @@ def test_an_approved_one_cannot_be_edited_or_withdrawn( # --- erasure -------------------------------------------------------------- def test_erasing_the_author_takes_their_submissions_and_photos( - app, repo, db, post, owner_id, maria, sign_in): + app, repo, db, post, superadmin_id, maria, sign_in): """A submission is private writing, so it goes the way private messages do. What remains of an approved one is the post in the repository, which carries their name in a commit that is not ours to rewrite from here.""" @@ -372,14 +372,14 @@ def test_erasing_the_author_takes_their_submissions_and_photos( propose(post, picture=(io.BytesIO(PNG), "feria.png")) stored = only_submission(db)["photo_name"] - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{maria}/eliminar") assert db.execute("SELECT COUNT(*) AS n FROM submissions").fetchone()["n"] == 0 assert not (Path(app.config["UPLOAD_DIR"]) / stored).exists() -def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria, +def test_erasing_a_reviewer_keeps_the_submission(db, post, superadmin_id, maria, make_member, sign_in): """Who reviewed something is a fact about the submission, not personal data of the reviewer, so the name goes and the row stays.""" @@ -390,7 +390,7 @@ def test_erasing_a_reviewer_keeps_the_submission(db, post, owner_id, maria, sign_in(reviewer) post(f"/comunidad/publicaciones/{submission_id}/rechazar", {"note": "Falta el dónde."}) - sign_in(owner_id) + sign_in(superadmin_id) post(f"/comunidad/miembros/{reviewer}/eliminar") row = only_submission(db) diff --git a/docs/server-setup.md b/docs/server-setup.md index e2ecba5..4e7cab7 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -521,43 +521,75 @@ has been archiving air" are otherwise the same empty line. ### 11.6 Who can do what -| | Responsable | Administrador | Moderador | Miembro | -|---|---|---|---|---| -| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | -| Private messages, own profile | ✓ | ✓ | ✓ | ✓ | -| Propose a public post | ✓ | ✓ | ✓ | ✓ | -| Publish a public post directly | ✓ | ✓ | ✓ | — | -| Approve or return a proposal | ✓ | ✓ | ✓ | — | -| Edit and delete published posts | ✓ | ✓ | ✓ | — | -| Static pages of the site | ✓ | ✓ | — | — | -| Delete any wall post | ✓ | ✓ | — | — | -| Edit someone else's post | — | — | — | — | -| Pin and close threads | ✓ | ✓ | — | — | -| Create members and moderators | ✓ | ✓ | — | — | -| Change a role (below admin) | ✓ | ✓ | — | — | -| Create admins, promote to admin | ✓ | — | — | — | -| Suspend a member or moderator | ✓ | ✓ | — | — | -| Suspend an admin | ✓ | — | — | — | -| Transfer ownership, erase a member | ✓ | — | — | — | +Five roles, and **two of them are single chairs held by the database** rather +than by the application: a partial unique index each, so a bug in a handler +cannot produce a second of either. + +| | Superadministrador | Responsable | Administrador | Moderador | Miembro | +|---|---|---|---|---|---| +| Wall: post, comment, edit own | ✓ | ✓ | ✓ | ✓ | ✓ | +| Private messages, own profile | ✓ | ✓ | ✓ | ✓ | ✓ | +| Propose a public post | ✓ | ✓ | ✓ | ✓ | ✓ | +| Publish a public post directly | ✓ | ✓ | ✓ | ✓ | — | +| Approve or return a proposal | ✓ | ✓ | ✓ | ✓ | — | +| Edit and delete published posts | ✓ | ✓ | ✓ | ✓ | — | +| Static pages of the site | ✓ | ✓ | ✓ | — | — | +| Delete any wall post, pin and close | ✓ | ✓ | ✓ | — | — | +| Edit someone else's post | — | — | — | — | — | +| Create members and moderators | ✓ | ✓ | ✓ | — | — | +| Change a role below admin | ✓ | ✓ | ✓ | — | — | +| Suspend a member or moderator | ✓ | ✓ | ✓ | — | — | +| Erase a member | ✓ | ✓ | — | — | — | +| Name the responsable | ✓ | ✓ | — | — | — | +| **Create, promote, suspend an admin** | ✓ | — | — | — | — | +| **Marca: the look and the identity** | ✓ | — | — | — | — | +| **Estado del sistema, Registro** | ✓ | — | — | — | — | +| **Hand the platform on** | ✓ | — | — | — | — | + +**The two chairs do different jobs, and that is the point.** The +*superadministrador* runs the **platform**: admin accounts, the look, the +identity, the system tools. The *responsable* runs the **association**: members, +moderators, invitations, erasure. Installed for a second organisation, the first +is whoever maintains the box and the second is their president — which is what +makes the responsable chair safe to hand to a customer, and why an admin account +is not theirs to grant. + +**Neither chair can be touched by anybody, including themselves.** The +superadministrator because there is nothing above them; the responsable because +the chair belongs to the association, and a platform administrator quietly +removing the president of the organisation they host is exactly the move this +separation exists to prevent. Each steps down by handing their own chair on, and +whoever gives one up becomes an administrator — there is no role above the one +they just gave away. **A moderator has no power over people.** They decide what the public reads and nothing else: no creating, suspending, promoting or erasing anybody. That line is the whole point of having the role — a moderator who could also suspend the author of a post they had just returned would be a second kind of administrator. -Admins can appoint moderators; only the owner can appoint admins. That rule lives -in one place (`may_create` in `apps/board/members.py`) and the role form on -*Miembros* checks it twice: once for reaching the person, once for the role being -given. +Both rules live in one place each — `may_create` and `may_manage` in +`apps/board/members.py` — and the role picker on a member's page is built from +`assignable_roles(actor)`, the same predicate, so it can never offer a role the +handler will refuse. "This role or anything above it" is `is_at_least` in +`apps/board/security.py`, over one ordered `LADDER`: it replaced seven literal +tuples scattered through the app, each of which had silently excluded the +superadministrator the moment a tier appeared above owner. Nobody edits anyone else's words, administrators included. Taking a post down is visible to the person who wrote it; rewriting it is not, and an admin who could do that could leave a sentence attributed to a member who never wrote it. -There is exactly one owner, and the database enforces it with a unique index -rather than trusting the application to remember. The owner cannot be suspended -or demoted by anyone, themselves included — to step down, transfer ownership to -an admin. +**On upgrade**, migration 7 promotes the existing owner — Pablo — to +superadministrator and leaves the responsable chair empty. Nothing is erased and +nobody has to type anything: a superadministrator passes every check an owner +passed. The chair is filled from *Miembros* → somebody's page → **Nombrar +responsable** whenever there is somebody to put in it. + +`BOARD_OWNER` keeps its name and now seeds a superadministrator. It refuses to +change an existing one, so editing the environment cannot hand anybody the +platform — and the `ON CONFLICT` clause that writes the role is pinned to +`superadmin` for a reason worth knowing: left saying `owner`, it would have +demoted the superadministrator on every container restart. ### 11.7 Personal data From 81d9fae4a9c641a4f7e692896866555ee6c0bb28 Mon Sep 17 00:00:00 2001 From: Pablo Volenski Date: Tue, 6 Oct 2026 12:18:04 +0000 Subject: [PATCH 2/2] =?UTF-8?q?Identidad,=20tipograf=C3=ADas,=20y=20tres?= =?UTF-8?q?=20herramientas=20de=20administraci=C3=B3n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The second half of the superadministrator's job: not just who may do things, but what they get to do that nobody else does. **Identidad** is everything that used to be frozen in config.yaml — the name and the one-line tagline in all three languages, the association's accounts elsewhere, a public email, a city and street, a share picture and the footer line. It commits data/site.yaml the way Marca commits data/brand.yaml. Hugo cannot have config.yaml overridden by a data file, so the name and tagline are read through two new partials that prefer the data file and fall back to the config; every template showing either calls one, so they cannot drift. A site with no data/site.yaml builds byte-for-byte what it built before — asserted by building both ways and diffing with the stylesheet fingerprint normalised. The contact fields are not decoration: they become ContactPoint and PostalAddress in the Organization schema, which is what puts an association in a local result rather than only a web one, and the social links become sameAs, which is how an engine knows an Instagram account and this site are one body. **Marca** grows a typeface and a roundness. Four system stacks — nothing downloaded, which is deliberate and a GDPR matter — or an uploaded .woff2, sniffed by its wOF2 signature, capped at 400 KB, named ahead of the old stack so a font that fails to load leaves a readable site. The fold-out warning covers missing accented glyphs, file size, synthesised bold, and licensing: a font is software, a desktop licence is not a webfont licence, and that liability follows the platform to every organisation it is installed for. SIL OFL and Apache-2.0 are named, with seven places to find them. **Three tools.** Estado del sistema exercises the content token against the repository rather than checking it is non-empty — "present" was never the problem, a wrong scope broke publishing for three phases while looking fine — and reports mail, backups, disk and every documented setting the container does not have. It changes nothing on purpose. Registro de actividad records the dozen acts that change who can do what; the actor is cleared and not cascaded on erasure, and log() never raises, because an administrator who could not be appointed because the note about it could not be saved is worse than a gap in the notes. Biblioteca de medios lists every picture with the posts that use it and, finally, shows the orphans — a picture whose post was deleted has stayed in the repository, deployed and unreferenced, for the life of this site with no way to see one. Two bugs found by looking at the rendered pages rather than at the tests: **Gestión had disappeared from the superadministrator's own navigation.** base.html asked `g.member.role in ('owner', 'admin')`, right until a role appeared above both. 622 tests passed while it was broken, because every one of them signed in as an admin or below. The templates now call the same `is_at_least` the handlers do, and test_navigation.py covers the tier above admin — verified by reintroducing the tuple and watching it fail. And the status screen counted the tombstone as a suspended member. Migration 8 is plain ADD COLUMNs; `activity` and `site` are new tables, so CREATE TABLE IF NOT EXISTS covers them with no step at all. The erase guard caught both the moment they existed, which is that test doing its job. 627 tests pass. Hugo builds clean with the pipeline's flags, both with and without the two data files. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn --- apps/board/activity.py | 95 ++++++ apps/board/app.py | 22 +- apps/board/brand.py | 272 ++++++++++++++-- apps/board/content.py | 11 +- apps/board/home.py | 3 +- apps/board/identity.py | 305 ++++++++++++++++++ apps/board/media.py | 104 ++++++ apps/board/members.py | 24 +- apps/board/migrations.py | 27 ++ apps/board/schema.sql | 61 ++++ apps/board/static/board.css | 63 ++++ apps/board/status.py | 191 +++++++++++ apps/board/submissions.py | 4 +- apps/board/templates/activity.html | 51 +++ apps/board/templates/base.html | 2 +- apps/board/templates/brand_form.html | 91 ++++++ apps/board/templates/gestion.html | 47 +++ apps/board/templates/identity_form.html | 112 +++++++ apps/board/templates/media.html | 47 +++ apps/board/templates/member.html | 2 +- apps/board/templates/members.html | 2 +- apps/board/templates/status.html | 49 +++ apps/board/tests/test_brand.py | 113 +++++++ apps/board/tests/test_navigation.py | 37 +++ apps/board/tests/test_tools.py | 260 +++++++++++++++ docs/server-setup.md | 85 ++++- themes/vienalatina/assets/css/main.css | 11 + .../vienalatina/layouts/_default/baseof.html | 2 +- .../layouts/partials/brand-head.html | 12 +- .../vienalatina/layouts/partials/footer.html | 18 +- .../vienalatina/layouts/partials/header.html | 5 +- .../layouts/partials/seo-head.html | 41 ++- .../layouts/partials/site-name.html | 20 ++ .../layouts/partials/site-tagline.html | 12 + 34 files changed, 2140 insertions(+), 61 deletions(-) create mode 100644 apps/board/activity.py create mode 100644 apps/board/identity.py create mode 100644 apps/board/media.py create mode 100644 apps/board/status.py create mode 100644 apps/board/templates/activity.html create mode 100644 apps/board/templates/identity_form.html create mode 100644 apps/board/templates/media.html create mode 100644 apps/board/templates/status.html create mode 100644 apps/board/tests/test_tools.py create mode 100644 themes/vienalatina/layouts/partials/site-name.html create mode 100644 themes/vienalatina/layouts/partials/site-tagline.html diff --git a/apps/board/activity.py b/apps/board/activity.py new file mode 100644 index 0000000..f2c4984 --- /dev/null +++ b/apps/board/activity.py @@ -0,0 +1,95 @@ +"""Who did what, for the superadministrator to read. + +An audit trail is the natural companion to a role that can do everything: the +question "who made them an administrator?" has no other answer, and the moment +anybody asks it is exactly the moment nobody can remember. + +**Deliberately not a general event store.** One row per act that changes who can +do what, or what the public sees. No page views, no successful sign-ins, no +"somebody opened Miembros" — a log that records everything is a log nobody +reads, and this one has to be readable by a person scrolling it once a month. + +`log()` never raises. A failure to write the diary must not fail the thing being +recorded: an administrator who could not be appointed because the note about it +could not be saved is a worse outcome than a gap in the notes. +""" + +from __future__ import annotations + +from flask import Blueprint, current_app, g, render_template, request + +from .db import get_db +from .security import superadmin_required + +bp = Blueprint("activity", __name__) + +PER_PAGE = 60 + +# action key -> the sentence a person reads. Built here rather than stored, +# because the stored key is what a later reader greps for and the wording is +# what changes. `{object}` is whatever the act was done to. +SENTENCES = { + "member.created": "dio de alta a {object}", + "member.invited": "envió una invitación a {object}", + "member.suspended": "suspendió a {object}", + "member.restored": "reactivó a {object}", + "member.erased": "eliminó a {object}", + "role.changed": "cambió el rol de {object}", + "chair.owner": "nombró responsable a {object}", + "chair.superadmin": "entregó la plataforma a {object}", + "submission.approved": "publicó la propuesta «{object}»", + "submission.rejected": "devolvió la propuesta «{object}»", + "content.published": "publicó «{object}»", + "content.deleted": "retiró «{object}»", + "brand.saved": "cambió el aspecto del sitio", + "brand.restored": "restauró el aspecto de fábrica", + "identity.saved": "cambió la identidad del sitio", + "media.deleted": "borró la imagen {object}", +} + + +def log(action: str, object_name: str = "", detail: str = "") -> None: + """Record one act. Call it after the thing succeeded, never before. + + Swallows everything on purpose — see the module docstring. The log line it + writes instead is what tells somebody the diary is broken. + """ + try: + get_db().execute( + "INSERT INTO activity (actor_id, action, object, detail) VALUES (?, ?, ?, ?)", + (g.member["id"] if getattr(g, "member", None) else None, + action, str(object_name)[:200], str(detail)[:400]), + ) + except Exception: # pragma: no cover - defensive + current_app.logger.warning("could not write activity %r", action, exc_info=True) + + +@bp.route("/gestion/registro") +@superadmin_required +def index(): + page = max(0, request.args.get("p", type=int) or 0) + rows = get_db().execute( + """SELECT a.*, m.display_name AS actor, m.gitea_login AS actor_login + FROM activity a + LEFT JOIN members m ON m.id = a.actor_id + ORDER BY a.created_at DESC, a.id DESC + LIMIT ? OFFSET ?""", + (PER_PAGE + 1, page * PER_PAGE), + ).fetchall() + # One more than a page, asked for so that "is there another page" is known + # without a second COUNT(*) over a table that only grows. + more = len(rows) > PER_PAGE + + # The sentence is built here rather than in the template: Jinja's `format` + # filter is printf-style, so a `{object}` placeholder would have rendered + # literally — and an unknown action falling back to its own key is what + # makes a log written by an older version still readable. + entries = [{ + "at": row["created_at"], + "actor": row["actor"], + "sentence": SENTENCES.get(row["action"], row["action"]).format( + object=row["object"] or "—"), + "detail": row["detail"], + } for row in rows[:PER_PAGE]] + + return render_template("activity.html", rows=entries, page=page, more=more) diff --git a/apps/board/app.py b/apps/board/app.py index 61f1ba5..9c09c52 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -14,7 +14,7 @@ from flask import Flask, render_template, request from werkzeug.middleware.proxy_fix import ProxyFix from .db import TOMBSTONE_LOGIN, close_db, init_db -from .security import check_csrf, csrf_token +from .security import check_csrf, csrf_token, is_at_least URL_PREFIX = "/comunidad" @@ -94,11 +94,16 @@ def create_app(overrides: dict | None = None) -> Flask: # restart, which is a confusing way to find out the variable is unset. raise RuntimeError("BOARD_SECRET_KEY is required (generate one with `openssl rand -hex 32`).") - from . import (auth, board, brand, content, events, home, members, - messages, profiles, submissions, uploads) + from . import (activity, auth, board, brand, content, events, home, + identity, media, members, messages, profiles, status, + submissions, uploads) app.register_blueprint(auth.bp, url_prefix=URL_PREFIX) app.register_blueprint(home.bp, url_prefix=URL_PREFIX) app.register_blueprint(brand.bp, url_prefix=URL_PREFIX) + app.register_blueprint(identity.bp, url_prefix=URL_PREFIX) + app.register_blueprint(status.bp, url_prefix=URL_PREFIX) + app.register_blueprint(activity.bp, url_prefix=URL_PREFIX) + app.register_blueprint(media.bp, url_prefix=URL_PREFIX) app.register_blueprint(submissions.bp, url_prefix=URL_PREFIX) app.register_blueprint(events.bp, url_prefix=URL_PREFIX) app.register_blueprint(members.bp, url_prefix=URL_PREFIX) @@ -122,6 +127,11 @@ def create_app(overrides: dict | None = None) -> Flask: # keeps the picker from offering a role the handler will refuse — with two # levels above admin, a hardcoded list can only be right for one of them. app.jinja_env.globals["assignable_roles"] = members.assignable_roles + # The same predicate the handlers use. Templates had their own literal + # tuples until a tier appeared above them and Gestión quietly disappeared + # from the superadministrator's own navigation — the exact failure + # `is_at_least` was introduced to end on the Python side. + app.jinja_env.globals["is_at_least"] = is_at_least @app.context_processor def _year(): @@ -134,6 +144,12 @@ def create_app(overrides: dict | None = None) -> Flask: # that would save the query by deferring it. return {"brand": brand.state()} + @app.context_processor + def _identity(): + # Only Gestión draws it, so unlike `brand` this one is lazy: a function + # the template calls, costing nothing on the pages that never ask. + return {"identity": identity.current} + @app.context_processor def _badges(): # Lazily, as functions: base.html is rendered for signed-out pages and diff --git a/apps/board/brand.py b/apps/board/brand.py index d52bf93..0cab105 100644 --- a/apps/board/brand.py +++ b/apps/board/brand.py @@ -49,11 +49,12 @@ from __future__ import annotations import colorsys import json import re +import secrets from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, render_template, request, send_from_directory, url_for) -from . import gitea, uploads +from . import activity, gitea, uploads from .db import get_db from .security import superadmin_required @@ -105,6 +106,50 @@ DERIVED = { HEX = re.compile(r"^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$") +# --- the typeface ---------------------------------------------------------- +# +# Four stacks of fonts that are already on the reader's machine, and nothing +# downloaded from anywhere. The site's freedom from Google Fonts is deliberate +# and a GDPR matter: a stylesheet that pulls a font from fonts.gstatic.com tells +# Google the IP address of everyone who reads this site, which is a disclosure +# an association cannot make on its visitors' behalf without asking them. +# +# A fifth option, `propia`, uses an uploaded .woff2 and falls back to the sans +# stack — so a font that fails to load leaves a readable site rather than a +# browser default. +TYPEFACES = { + "sans": ("Sans (la de ahora)", + '"Montserrat", -apple-system, BlinkMacSystemFont, "Segoe UI", ' + 'Roboto, "Helvetica Neue", Arial, sans-serif'), + "serif": ("Serif", + 'Georgia, Cambria, "Times New Roman", Times, serif'), + "redonda": ("Redondeada", + '"Trebuchet MS", "Segoe UI", Verdana, sans-serif'), + "sistema": ("La del sistema", + 'system-ui, -apple-system, "Segoe UI", Roboto, sans-serif'), +} +DEFAULT_TYPEFACE = "sans" +FONT_STACK_FALLBACK = TYPEFACES["sans"][1] + +# A .woff2 and nothing else. It is the web format — every browser in use takes +# it, it is the smallest, and it has a four-byte signature this can check +# without a parser. A .ttf or .otf would work in a browser and would also be +# two to five times the size for the same letters. +FONT_SIGNATURE = b"wOF2" +FONT_MAX_BYTES = 400_000 + +# How round everything is. One setting driving four tokens, because a site whose +# cards are round and whose buttons are square looks like two sites. +ROUNDNESS = { + "suave": ("Suave (la de ahora)", {"radius-xl": "18px", "radius-lg": "12px", + "radius-md": "8px", "radius-sm": "5px"}), + "recta": ("Recta", {"radius-xl": "0", "radius-lg": "0", + "radius-md": "0", "radius-sm": "0"}), + "redonda": ("Redonda", {"radius-xl": "28px", "radius-lg": "20px", + "radius-md": "14px", "radius-sm": "10px"}), +} +DEFAULT_ROUNDNESS = "suave" + # The free CSS box takes anything but these. `<` and `>` cannot appear in valid # CSS outside a string, and they are the two characters that could end the # stylesheet context in a consumer that mishandles it. Everything else is left @@ -236,25 +281,43 @@ def current() -> dict: stored = {} if not isinstance(stored, dict): stored = {} + def column(name): + return (row[name] if row else None) or None + + typeface = column("typeface") + if typeface not in TYPEFACES and typeface != "propia": + typeface = DEFAULT_TYPEFACE + roundness = column("roundness") + if roundness not in ROUNDNESS: + roundness = DEFAULT_ROUNDNESS + return { "stored": stored, "tokens": resolve(stored), "custom_css": (row["custom_css"] if row else "") or "", - "logo_name": row["logo_name"] if row else None, - "favicon_name": row["favicon_name"] if row else None, + "logo_name": column("logo_name"), + "favicon_name": column("favicon_name"), + "font_name": column("font_name"), + "typeface": typeface, + "roundness": roundness, "updated_at": row["updated_at"] if row else None, "published_at": row["published_at"] if row else None, "stamp": _stamp(row["updated_at"] if row else None), "customised": bool(stored or (row and (row["custom_css"] or row["logo_name"] - or row["favicon_name"]))), + or row["favicon_name"] + or column("font_name") + or typeface != DEFAULT_TYPEFACE + or roundness != DEFAULT_ROUNDNESS))), } def _blank() -> dict: """The factory look, as `current()` would describe it.""" return {"stored": {}, "tokens": dict(FACTORY), "custom_css": "", - "logo_name": None, "favicon_name": None, "updated_at": None, - "published_at": None, "stamp": "0", "customised": False} + "logo_name": None, "favicon_name": None, "font_name": None, + "typeface": DEFAULT_TYPEFACE, "roundness": DEFAULT_ROUNDNESS, + "updated_at": None, "published_at": None, "stamp": "0", + "customised": False} def state() -> dict: @@ -283,20 +346,74 @@ def _stamp(updated_at: str | None) -> str: return re.sub(r"\D", "", updated_at or "") or "0" -def stylesheet(state: dict | None = None) -> str: - """The `:root` overrides and then the custom CSS, in that order. +def font_stack(state: dict) -> str | None: + """The `font-family` the site should use, or None to leave it alone. - Only the tokens that differ from the factory are written, so the file reads - as what the admin changed, and an install that has changed nothing serves a + None rather than the default string when nothing was chosen, so a site that + has not touched this serves no font rule at all and the stylesheets stay + byte-identical to what they were. + + An uploaded face is named first and the sans stack follows it: a font that + 404s or arrives corrupt then leaves a readable site rather than whatever the + browser falls back to on its own. + """ + if state["typeface"] == "propia" and state["font_name"]: + return f'"VLPropia", {FONT_STACK_FALLBACK}' + if state["typeface"] in TYPEFACES and state["typeface"] != DEFAULT_TYPEFACE: + return TYPEFACES[state["typeface"]][1] + return None + + +def _radius_tokens(state: dict) -> dict: + """The four radius values, or nothing when the roundness is the built-in.""" + if state["roundness"] == DEFAULT_ROUNDNESS: + return {} + return ROUNDNESS[state["roundness"]][1] + + +def font_face(state: dict, url: str) -> str: + """The `@font-face` for an uploaded typeface, at whatever URL serves it. + + `font-display: swap` deliberately: the alternative shows nothing until the + file arrives, and a blank article on a slow phone is worse than an article + that changes typeface a moment after it appears. + """ + return ("@font-face {\n" + '\tfont-family: "VLPropia";\n' + f"\tsrc: url({url}) format('woff2');\n" + "\tfont-weight: 100 900;\n" + "\tfont-display: swap;\n" + "}\n") + + +def stylesheet(state: dict | None = None) -> str: + """The `@font-face`, the `:root` overrides, then the custom CSS, in that + order. + + Only what differs from the factory is written, so the file reads as what the + superadministrator changed, and an install that has changed nothing serves a comment and no rules at all. """ state = state or current() + css = "/* Generado desde Gestión → Marca. No editar a mano. */\n" + + if state["typeface"] == "propia" and state["font_name"]: + css += font_face(state, url_for("brand.picture", + stored_name=state["font_name"])) + lines = [f"\t--{name}: {value};" for name, value in state["tokens"].items() if value != FACTORY[name]] - css = "/* Generado desde Gestión → Marca. No editar a mano. */\n" + lines += [f"\t--{name}: {value};" for name, value in _radius_tokens(state).items()] if lines: css += ":root {\n" + "\n".join(lines) + "\n}\n" + + stack = font_stack(state) + if stack: + # On `body` rather than `:root`, because the rule it is overriding is on + # `body` and a custom property would need every rule to opt in. + css += f"body {{ font-family: {stack}; }}\n" + if state["custom_css"]: # Last, so it wins over everything above it. That is the whole contract # of the advanced box. @@ -369,6 +486,52 @@ def _read_picture(field: str, allowed: tuple[str, ...], errors: list[str]): return item +def _read_font(errors: list[str]): + """The uploaded typeface, sniffed rather than trusted. + + Not through `uploads.stage`, which knows about pictures: this needs its own + four-byte check and its own size limit. Same shape though, and the same + rule — the name on the file decides nothing. + + A stored name that ends `.woff2` would not match `uploads.STORED_NAME`, + which allows three or four letters; `.wof` would be a lie. So the file is + stored as `.bin` and served with an explicit Content-Type, which is what the + browser reads anyway. + """ + upload = request.files.get("font") + if not upload or not upload.filename: + return None + data = upload.read() + if not data: + return None + if len(data) > FONT_MAX_BYTES: + errors.append( + f"La tipografía pesa {len(data) // 1024}KB y el máximo son " + f"{FONT_MAX_BYTES // 1024}KB. Subconjunta la fuente a latín y " + "latín extendido antes de subirla." + ) + return None + if not data.startswith(FONT_SIGNATURE): + errors.append( + f"«{upload.filename[:60]}» no es un .woff2. Es el único formato que " + "se acepta: es el de la web, lo entienden todos los navegadores y " + "es el más pequeño." + ) + return None + return { + "data": data, + "original_name": upload.filename[:200], + "stored_name": f"tipografia-{secrets.token_hex(6)}.bin", + } + + +def _read_choice(form, field: str, table: dict, default: str, + extra: tuple[str, ...] = ()) -> str: + """One key from a table of our own, or the default. Never the raw value.""" + choice = (form.get(field) or "").strip() + return choice if choice in table or choice in extra else default + + # --- routes ---------------------------------------------------------------- @bp.route("/gestion/marca", methods=["GET", "POST"]) @@ -379,6 +542,7 @@ def edit(): return render_template("brand_form.html", state=state, factory=FACTORY, simple=SIMPLE, derived=sorted(DERIVED), advanced=_advanced(), + typefaces=TYPEFACES, roundness=ROUNDNESS, notes=warnings(state["tokens"])) errors: list[str] = [] @@ -386,18 +550,31 @@ def edit(): css = _read_css(request.form, errors) logo = _read_picture("logo", LOGO_EXTENSIONS, errors) favicon = _read_picture("favicon", FAVICON_EXTENSIONS, errors) + font = _read_font(errors) + typeface = _read_choice(request.form, "typeface", TYPEFACES, + DEFAULT_TYPEFACE, extra=("propia",)) + roundness = _read_choice(request.form, "roundness", ROUNDNESS, DEFAULT_ROUNDNESS) if errors: for message in errors: flash(message, "error") return redirect(url_for("brand.edit")) state = current() + if typeface == "propia" and not (font or state["font_name"]): + # Chosen without ever uploading one. Refused rather than silently + # falling back, because the site would look unchanged and the setting + # would say otherwise. + flash("Para usar una tipografía propia hay que subir un archivo .woff2.", + "error") + return redirect(url_for("brand.edit")) + # Written before the commits: the members area must not depend on the git # server being up to change its own colours. - _store(stored, css, logo, favicon, state) + _store(stored, css, logo, favicon, font, typeface, roundness, state) for note in warnings(resolve(stored)): flash(note, "error") + activity.log("brand.saved") if _publish(): flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok") return redirect(url_for("brand.edit")) @@ -409,15 +586,19 @@ def _advanced() -> tuple: return tuple(name for name in FACTORY if name not in simple) -def _store(stored: dict, css: str, logo, favicon, state: dict) -> None: - """The row, and the two pictures on disk. +def _store(stored: dict, css: str, logo, favicon, font, typeface: str, + roundness: str, state: dict) -> None: + """The row, and the three uploaded files on disk. Files before the row, as `uploads.save` does it and for the same reason: a row naming a file that is not there renders as a broken image on every future visit, while a file with no row is invisible. """ - names = {"logo_name": state["logo_name"], "favicon_name": state["favicon_name"]} - for field, item in (("logo_name", logo), ("favicon_name", favicon)): + names = {"logo_name": state["logo_name"], + "favicon_name": state["favicon_name"], + "font_name": state["font_name"]} + uploaded = (("logo_name", logo), ("favicon_name", favicon), ("font_name", font)) + for field, item in uploaded: if item is None: continue uploads.directory().joinpath(item["stored_name"]).write_bytes(item["data"]) @@ -425,23 +606,28 @@ def _store(stored: dict, css: str, logo, favicon, state: dict) -> None: get_db().execute( """INSERT INTO brand (id, tokens_json, custom_css, logo_name, favicon_name, + font_name, typeface, roundness, updated_by, updated_at, published_at) - VALUES (1, ?, ?, ?, ?, ?, datetime('now'), NULL) + VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), NULL) ON CONFLICT(id) DO UPDATE SET tokens_json = excluded.tokens_json, custom_css = excluded.custom_css, logo_name = excluded.logo_name, favicon_name = excluded.favicon_name, + font_name = excluded.font_name, + typeface = excluded.typeface, + roundness = excluded.roundness, updated_by = excluded.updated_by, updated_at = excluded.updated_at, published_at = NULL""", (json.dumps(stored, sort_keys=True), css, - names["logo_name"], names["favicon_name"], g.member["id"]), + names["logo_name"], names["favicon_name"], names["font_name"], + typeface, roundness, g.member["id"]), ) - # The old pictures, once nothing points at them. After the row, so a - # rollback cannot leave the row naming a file that has been deleted. - for field, item in (("logo_name", logo), ("favicon_name", favicon)): + # The old files, once nothing points at them. After the row, so a rollback + # cannot leave the row naming a file that has been deleted. + for field, item in uploaded: if item is not None and state[field] and state[field] != names[field]: uploads.remove(state[field]) @@ -465,9 +651,10 @@ def restore(): """ state = current() get_db().execute("DELETE FROM brand WHERE id = 1") - for name in (state["logo_name"], state["favicon_name"]): + for name in (state["logo_name"], state["favicon_name"], state["font_name"]): if name: uploads.remove(name) + activity.log("brand.restored") flash("Restaurado lo de fábrica.", "ok") _publish() return redirect(url_for("brand.edit")) @@ -498,8 +685,16 @@ def picture(stored_name: str): if not uploads.STORED_NAME.match(stored_name): abort(404) state = current() - if stored_name not in (state["logo_name"], state["favicon_name"]): + if stored_name not in (state["logo_name"], state["favicon_name"], + state["font_name"]): abort(404) + # The typeface is stored `.bin` — `.woff2` is five characters and + # `STORED_NAME` allows three or four — so its type is stated here rather + # than guessed from the name. A font served as application/octet-stream + # loads anyway, but says nothing true in a network panel. + if stored_name == state["font_name"]: + return send_from_directory(uploads.directory(), stored_name, + mimetype="font/woff2") return send_from_directory(uploads.directory(), stored_name) @@ -512,10 +707,15 @@ def _repo_path(stored_name: str, kind: str) -> str: file instead of leaving every previous one in the repository, deployed and unreferenced. """ - return f"{REPO_FOLDER}/{kind}.{stored_name.rsplit('.', 1)[-1]}" + # The typeface is stored locally as `.bin` — see `_read_font` — but the + # repository is a web root, where the extension is what a reader's cache and + # a CDN go by. It lands as `.woff2`, which is what it is. + extension = "woff2" if kind == "font" else stored_name.rsplit(".", 1)[-1] + return f"{REPO_FOLDER}/{kind}.{extension}" -def _yaml(state: dict, logo: str | None, favicon: str | None) -> str: +def _yaml(state: dict, logo: str | None, favicon: str | None, + font: str | None = None) -> str: """`data/brand.yaml`, written rather than dumped. By hand because the values are known: colours matched against a hex @@ -531,6 +731,14 @@ def _yaml(state: dict, logo: str | None, favicon: str | None) -> str: for name, value in state["tokens"].items(): if value != FACTORY[name]: lines.append(f" {name}: \"{value}\"") + for name, value in _radius_tokens(state).items(): + lines.append(f" {name}: \"{value}\"") + stack = font_stack(state) + if stack: + # Single-quoted because every stack has double quotes inside it. + lines.append(f"font_stack: '{stack}'") + if font: + lines.append(f"font: \"/{font.removeprefix('static/')}\"") if logo: lines.append(f"logo: \"/{logo.removeprefix('static/')}\"") if favicon: @@ -561,21 +769,21 @@ def _publish() -> bool: return False try: - logo_path = favicon_path = None + paths = {} for kind, name in (("logo", state["logo_name"]), - ("favicon", state["favicon_name"])): + ("favicon", state["favicon_name"]), + ("font", state["font_name"])): if not name: continue path = _repo_path(name, kind) data = uploads.directory().joinpath(name).read_bytes() _write(path, data, f"marca: {kind}", token) _tidy(kind, path, token) - if kind == "logo": - logo_path = path - else: - favicon_path = path + paths[kind] = path - _write(DATA_FILE, _yaml(state, logo_path, favicon_path).encode("utf-8"), + _write(DATA_FILE, + _yaml(state, paths.get("logo"), paths.get("favicon"), + paths.get("font")).encode("utf-8"), "marca: colores", token) except (gitea.GiteaError, OSError) as exc: current_app.logger.warning("brand publish failed: %s", exc) diff --git a/apps/board/content.py b/apps/board/content.py index bbcdd2b..1cd24f2 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -172,17 +172,22 @@ def _cache_read(path: str, sha: str): def _cache_write(path: str, sha: str, fm: dict) -> None: get_db().execute( - """INSERT INTO content_cache (path, sha, title, date, generated, + """INSERT INTO content_cache (path, sha, title, date, generated, image, event_date, event_time, event_location) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET sha = excluded.sha, title = excluded.title, date = excluded.date, - generated = excluded.generated, + generated = excluded.generated, image = excluded.image, event_date = excluded.event_date, event_time = excluded.event_time, event_location = excluded.event_location, updated_at = datetime('now')""", (path, sha, str(fm.get("title", "")), str(fm.get("date", "")), 1 if fm.get("translated_from") else 0, + # Which picture this post carries, for the media library: without it, + # answering "does anything use this image?" means re-reading every + # post's frontmatter from the git server on every page view — the exact + # cost this cache exists to avoid. + str(fm.get("image", "") or ""), # Cached for the private calendar, which shows public events beside the # internal ones and would otherwise read every post's frontmatter on # every page view to find out when they are. diff --git a/apps/board/home.py b/apps/board/home.py index 4fa6ec4..ce7e458 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -181,7 +181,8 @@ def gestion(): "SELECT COUNT(*) AS n FROM members WHERE active = 0 AND role != 'tombstone'" ).fetchone()["n"], "moderators": db.execute( - "SELECT COUNT(*) AS n FROM members WHERE role IN ('owner', 'admin', 'moderator')" + "SELECT COUNT(*) AS n FROM members WHERE role IN " + "('superadmin', 'owner', 'admin', 'moderator')" ).fetchone()["n"], "pending": db.execute( "SELECT COUNT(*) AS n FROM submissions WHERE state = 'pending'").fetchone()["n"], diff --git a/apps/board/identity.py b/apps/board/identity.py new file mode 100644 index 0000000..2c768c5 --- /dev/null +++ b/apps/board/identity.py @@ -0,0 +1,305 @@ +"""What the site is called, what it says it is, and where to find it. + +Separate from `brand.py`, which is how the site *looks*, because the two have +different audiences and different failure modes: a wrong colour is ugly and a +wrong contact address is a message nobody receives. They are also published to +different files, so an organisation can change its tagline without touching its +palette. + +Everything here used to live in `config.yaml`, which means it could only be +changed by somebody with the repository — the one thing this phase exists to +end. The same arrangement `brand.py` uses carries it: SQLite first for the +members area, then a commit of `data/site.yaml` for the public site, in that +order so a git outage never blocks a change that does not need git. + +**Hugo cannot have `config.yaml` overridden by a data file**, so the name and +the tagline are read through `partials/site-name.html` and +`partials/site-tagline.html`, which prefer `site.Data.site` and fall back to the +config. Every template that shows either calls one of them, so the two cannot +drift — and a site with no `data/site.yaml` renders exactly what it rendered +before any of this existed. +""" + +from __future__ import annotations + +import json +import re + +from flask import (Blueprint, current_app, flash, g, redirect, + render_template, request, url_for) + +from . import activity, gitea +from .db import get_db +from .security import superadmin_required + +bp = Blueprint("identity", __name__) + +DATA_FILE = "data/site.yaml" + +# The languages the site is built in, with the config.yaml values they fall back +# to. Written here rather than read from config.yaml because the members area +# does not parse the site's configuration — and because a fallback that silently +# follows a file somebody edits is a fallback nobody can predict. +LANGUAGES = ( + ("es", "Español", "Viena Latina", + "Comunidad latinoamericana en Viena — turismo, cultura, gastronomía, " + "comunidad y comercio."), + ("de", "Deutsch", "Viena Latina", + "Lateinamerikanische Community in Wien — Tourismus, Kultur, Gastronomie, " + "Gemeinschaft und Handel."), + ("pt-br", "Português (Brasil)", "Viena Latina", + "Comunidade latino-americana em Viena — turismo, cultura, gastronomia, " + "comunidade e comércio."), +) + +# The networks offered, in the order they are drawn. A fixed list rather than a +# free "add a link" box: these become `sameAs` in the Organization schema, which +# is a claim that an account and this site are the same body — and a list of +# arbitrary URLs is not that claim, it is a bookmark bar. +NETWORKS = ( + ("instagram", "Instagram", "https://instagram.com/…"), + ("facebook", "Facebook", "https://facebook.com/…"), + ("whatsapp", "WhatsApp", "https://chat.whatsapp.com/…"), + ("youtube", "YouTube", "https://youtube.com/@…"), + ("mastodon", "Mastodon", "https://mastodon.social/@…"), + ("bluesky", "Bluesky", "https://bsky.app/profile/…"), +) + +NAME_MAX = 80 +TAGLINE_MAX = 300 +FOOTER_MAX = 200 + +# Same rule as a profile link, and for the same reason: `javascript:` in an href +# is a script running on vienalatina.com, and these are rendered in the footer of +# every page. +URL_RE = re.compile(r"^https?://[^\s<>\"']{3,300}$") +EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s.]+\.[^@\s]{2,}$") + + +def _row(): + return get_db().execute("SELECT * FROM site WHERE id = 1").fetchone() + + +def _loads(raw) -> dict: + try: + value = json.loads(raw or "{}") + except (TypeError, ValueError): + return {} + return value if isinstance(value, dict) else {} + + +def current() -> dict: + """Everything the form and both halves of the site read. + + Works with no row at all, which is every install until somebody opens the + screen — so the defaults here are the values `config.yaml` has today. + """ + row = _row() + names = _loads(row["names_json"] if row else None) + social = _loads(row["social_json"] if row else None) + + languages = {} + for code, _label, name, tagline in LANGUAGES: + given = names.get(code) if isinstance(names.get(code), dict) else {} + languages[code] = { + "name": (given.get("name") or "").strip() or name, + "tagline": (given.get("tagline") or "").strip() or tagline, + # What was actually stored, for the form: a field showing the + # fallback as its value would save the fallback the first time + # anybody pressed the button, freezing it. + "stored_name": (given.get("name") or "").strip(), + "stored_tagline": (given.get("tagline") or "").strip(), + } + + def column(name, default=""): + return ((row[name] if row else None) or default) + + return { + "languages": languages, + "social": {key: social.get(key, "") for key, _, _ in NETWORKS}, + "email": column("email"), + "phone": column("phone"), + "city": column("city"), + "street": column("street"), + "share_image": column("share_image"), + "footer_text": column("footer_text"), + "updated_at": row["updated_at"] if row else None, + "published_at": row["published_at"] if row else None, + "customised": row is not None, + } + + +def _read(form, errors: list[str]) -> dict: + """The whole form, checked. Nothing here is written as it arrived.""" + names = {} + for code, label, _name, _tagline in LANGUAGES: + name = (form.get(f"name-{code}") or "").strip()[:NAME_MAX] + tagline = (form.get(f"tagline-{code}") or "").strip()[:TAGLINE_MAX] + # One line, always: a tagline with a newline in it is an og:description + # that renders raggedly in some readers and truncated in others. + tagline = re.sub(r"\s+", " ", tagline) + if name or tagline: + names[code] = {"name": name, "tagline": tagline} + + social = {} + for key, label, _placeholder in NETWORKS: + url = (form.get(f"social-{key}") or "").strip() + if not url: + continue + if not URL_RE.match(url): + errors.append(f"La dirección de {label} tiene que empezar por https://.") + continue + social[key] = url + + email = (form.get("email") or "").strip()[:120] + if email and not EMAIL_RE.match(email): + errors.append("Ese correo de contacto no parece una dirección.") + email = "" + + share = (form.get("share_image") or "").strip() + if share and not re.match(r"^/uploads/[A-Za-z0-9._-]+$", share): + errors.append("La imagen al compartir tiene que ser una de /uploads/.") + share = "" + + return { + "names": names, "social": social, "email": email, + "phone": (form.get("phone") or "").strip()[:40], + "city": (form.get("city") or "").strip()[:80], + "street": (form.get("street") or "").strip()[:160], + "share_image": share, + "footer_text": (form.get("footer_text") or "").strip()[:FOOTER_MAX], + } + + +# --- routes ---------------------------------------------------------------- + +@bp.route("/gestion/identidad", methods=["GET", "POST"]) +@superadmin_required +def edit(): + if request.method == "GET": + return render_template("identity_form.html", state=current(), + languages=LANGUAGES, networks=NETWORKS) + + errors: list[str] = [] + fields = _read(request.form, errors) + if errors: + for message in errors: + flash(message, "error") + return redirect(url_for("identity.edit")) + + get_db().execute( + """INSERT INTO site (id, names_json, social_json, email, phone, city, + street, share_image, footer_text, + updated_by, updated_at, published_at) + VALUES (1, ?, ?, ?, ?, ?, ?, ?, ?, ?, datetime('now'), NULL) + ON CONFLICT(id) DO UPDATE SET + names_json = excluded.names_json, + social_json = excluded.social_json, + email = excluded.email, phone = excluded.phone, + city = excluded.city, street = excluded.street, + share_image = excluded.share_image, + footer_text = excluded.footer_text, + updated_by = excluded.updated_by, + updated_at = excluded.updated_at, + published_at = NULL""", + (json.dumps(fields["names"], sort_keys=True, ensure_ascii=False), + json.dumps(fields["social"], sort_keys=True), fields["email"], + fields["phone"], fields["city"], fields["street"], + fields["share_image"], fields["footer_text"], g.member["id"]), + ) + activity.log("identity.saved") + if _publish(): + flash("Guardado. El sitio público se reconstruye en un par de minutos.", "ok") + return redirect(url_for("identity.edit")) + + +@bp.route("/gestion/identidad/publicar", methods=["POST"]) +@superadmin_required +def publish(): + if _publish(): + flash("Publicado. El sitio público se reconstruye en un par de minutos.", "ok") + return redirect(url_for("identity.edit")) + + +# --- the public site's copy ------------------------------------------------ + +def _quote(value: str) -> str: + """A double-quoted YAML scalar. Backslashes and quotes are the only two + characters that can end one, and both are escapable inside it.""" + return '"' + value.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def yaml_for(state: dict) -> str: + """`data/site.yaml`, written rather than dumped — the same trade `brand.py` + makes, for the same reason: PyYAML is not a dependency of the members area + and is not worth becoming one for thirty lines of output. + + Only what was actually stored is written. A file repeating `config.yaml`'s + own values back at it would make the fallback meaningless and freeze the + defaults at whatever this version thought they were. + """ + lines = ["# Generado desde Gestión → Identidad en vienalatina.com/comunidad.", + "# No editar a mano: el próximo guardado lo sobrescribe."] + + languages = {code: data for code, data in state["languages"].items() + if data["stored_name"] or data["stored_tagline"]} + if languages: + lines.append("languages:") + for code, data in languages.items(): + lines.append(f" {code}:") + if data["stored_name"]: + lines.append(f" name: {_quote(data['stored_name'])}") + if data["stored_tagline"]: + lines.append(f" tagline: {_quote(data['stored_tagline'])}") + + social = [url for url in state["social"].values() if url] + if social: + # A flat list, because `sameAs` is a list of URLs and the names of the + # networks are nowhere in the schema. + lines.append("sameAs:") + lines += [f" - {_quote(url)}" for url in social] + lines.append("social:") + for key, url in state["social"].items(): + if url: + lines.append(f" {key}: {_quote(url)}") + + for key in ("email", "phone", "city", "street", "share_image", "footer_text"): + if state[key]: + lines.append(f"{key}: {_quote(state[key])}") + + return "\n".join(lines) + "\n" + + +def _publish() -> bool: + """Commit the identity. True if it got there. + + Returns False and says why rather than raising, exactly as `brand._publish` + does: the values are already saved here, and a superadministrator whose + change took effect in the members area needs to know the public site is a + step behind, not to meet a traceback. + """ + state = current() + try: + token = gitea.content_token() + except gitea.GiteaError as exc: + flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error") + return False + + # The contents API wants the current sha to replace a file and refuses one + # when creating, so the read comes first and a missing file is the normal + # case the first time. Same shape as `brand._write`. + try: + _, sha = gitea.read_file(DATA_FILE, token) + except gitea.GiteaError: + sha = None + + try: + gitea.write_file(DATA_FILE, yaml_for(state).encode("utf-8"), + "identidad: datos del sitio", token, sha=sha) + except (gitea.GiteaError, OSError) as exc: + current_app.logger.warning("identity publish failed: %s", exc) + flash(f"Guardado aquí. El sitio público no se ha actualizado: {exc}", "error") + return False + + get_db().execute("UPDATE site SET published_at = datetime('now') WHERE id = 1") + return True diff --git a/apps/board/media.py b/apps/board/media.py new file mode 100644 index 0000000..e8348d6 --- /dev/null +++ b/apps/board/media.py @@ -0,0 +1,104 @@ +"""Biblioteca de medios — every picture the public site carries. + +WordPress's Media Library, and the reason it earns a place here is narrower than +WordPress's: **nothing has ever been able to see an orphan.** A picture is +committed to `static/uploads/` when a post is written; delete the post and the +picture stays in the repository, deployed, referenced by nothing, for good. +There has been no way to list them, no way to notice, and no way to remove one +short of a commit by hand. + +So this is a listing with one question answered per row — which posts use this — +and one action: delete the ones nobody uses. + +**Open to administrators**, unlike the rest of Gestión's new screens. They are +the people who upload, so they are the people who should be able to see what +they have uploaded; and the worst an administrator can do here is remove a +picture from a post they could already have edited. +""" + +from __future__ import annotations + +from flask import (Blueprint, abort, flash, redirect, render_template, request, + url_for) + +from . import activity, content, gitea +from .db import get_db +from .security import admin_required + +bp = Blueprint("media", __name__) + +FOLDER = content.UPLOAD_FOLDER # static/uploads + + +def _users() -> dict[str, list[str]]: + """Which posts reference which picture, from the cache the listing fills. + + From `content_cache.image` rather than by reading every post's frontmatter: + the whole point of that cache is that a page like this one costs one + directory request to the git server rather than one request per post. + + A path appears in frontmatter as `/uploads/foto-abc.jpg`; the repository + calls it `static/uploads/foto-abc.jpg`. The basename is what both agree on. + """ + rows = get_db().execute( + "SELECT title, image FROM content_cache WHERE image IS NOT NULL AND image != ''" + ).fetchall() + used: dict[str, list[str]] = {} + for row in rows: + used.setdefault(row["image"].rsplit("/", 1)[-1], []).append(row["title"]) + return used + + +@bp.route("/gestion/medios") +@admin_required +def index(): + used = _users() + try: + files = gitea.list_directory(FOLDER, gitea.content_token()) + except (gitea.GiteaError, OSError) as exc: + flash(f"No se pudo leer la carpeta de imágenes: {exc}", "error") + files = [] + + items = [] + for entry in files: + name = entry.get("name", "") + items.append({ + "name": name, + "url": f"/uploads/{name}", + "sha": entry.get("sha", ""), + "size": (entry.get("size") or 0) // 1024, + "posts": used.get(name, []), + }) + # Orphans first: they are the only rows anybody has to act on, and a + # listing sorted by name buries them among the ones doing their job. + items.sort(key=lambda item: (bool(item["posts"]), item["name"])) + return render_template("media.html", items=items, + orphans=sum(1 for i in items if not i["posts"])) + + +@bp.route("/gestion/medios//eliminar", methods=["POST"]) +@admin_required +def delete(name: str): + """Remove a picture nobody uses. + + **Refuses one that is in use**, from the handler and not only by hiding the + button: deleting a referenced picture leaves a broken image on a published + page, which is worse than an orphan nobody sees. + """ + if "/" in name or name.startswith("."): + abort(404) + if _users().get(name): + flash("Esa imagen está en uso. Quítala del artículo primero.", "error") + return redirect(url_for("media.index")) + + sha = (request.form.get("sha") or "").strip() + try: + gitea.delete_file(f"{FOLDER}/{name}", sha, f"medios: retirar {name}", + gitea.content_token()) + except (gitea.GiteaError, OSError) as exc: + flash(f"No se pudo borrar: {exc}", "error") + return redirect(url_for("media.index")) + + activity.log("media.deleted", name) + flash(f"{name} borrada. El sitio se reconstruye en un par de minutos.", "ok") + return redirect(url_for("media.index")) diff --git a/apps/board/members.py b/apps/board/members.py index c7cfe4f..e4cf561 100644 --- a/apps/board/members.py +++ b/apps/board/members.py @@ -30,7 +30,7 @@ import sqlite3 from flask import (Blueprint, Response, abort, current_app, flash, g, redirect, render_template, request, url_for) -from . import auth, invites, mail, messages, profiles, uploads +from . import activity, auth, invites, mail, messages, profiles, uploads from .db import TOMBSTONE_LOGIN, get_db from .render import to_html from .security import (admin_required, login_required, owner_required, @@ -153,9 +153,15 @@ CLEARED_ON_ERASE = { # admin who typed it in: the meeting still happens after they leave, so the # row stays and the name goes. ("events", "created_by"), - # Same for the colours and the logo. An admin leaving is not a reason for - # the site to go back to looking like a default install. + # Same for the colours and the logo. Whoever set them leaving is not a + # reason for the site to go back to looking like a default install. ("brand", "updated_by"), + ("site", "updated_by"), + # That a role was changed is the association's record; whose name was on it + # is the erased person's data. The row stays, the name goes — which is also + # why the log is not a cascade: an audit trail that deletes itself when the + # person who triggered it leaves is not an audit trail. + ("activity", "actor_id"), } # Private correspondence is not reassigned to the tombstone, it goes. A thread @@ -422,6 +428,8 @@ def new(): except mail.MailFailed: invite_link, mail_problem = link, "failed" + activity.log("member.created", display_name or login, + f"rol: {ROLE_LABELS[role]}") return render_template("member_created.html", login=login, email=email, created=True, invite_link=invite_link, mail_problem=mail_problem, @@ -463,6 +471,7 @@ def invite(member_id: int): flash(f"No se pudo enviar el correo. Pásale este enlace: {link}", "error") return redirect(_page(target)) + activity.log("member.invited", target["display_name"], target["email"]) flash(f"Invitación enviada a {target['email']}.", "ok") return redirect(_page(target)) @@ -475,6 +484,8 @@ def set_active(member_id: int): abort(403) active = 1 if request.form.get("active") == "1" else 0 get_db().execute("UPDATE members SET active = ? WHERE id = ?", (active, member_id)) + activity.log("member.restored" if active else "member.suspended", + target["display_name"]) flash(f"{target['display_name']}: acceso {'restaurado' if active else 'suspendido'}.", "ok") return redirect(_page(target)) @@ -499,6 +510,8 @@ def set_role(member_id: int): if not may_create(g.member["role"], role): abort(403) get_db().execute("UPDATE members SET role = ? WHERE id = ?", (role, member_id)) + activity.log("role.changed", target["display_name"], + f"{ROLE_LABELS[target['role']]} → {ROLE_LABELS[role]}") flash(f"{target['display_name']} ahora es {ROLE_LABELS[role].lower()}.", "ok") return redirect(_page(target)) @@ -513,6 +526,7 @@ def transfer(member_id: int): flash("Solo puedes nombrar responsable a un miembro activo.", "error") return redirect(_page(target)) transfer_ownership(get_db(), g.member["id"], target["id"], "owner") + activity.log("chair.owner", target["display_name"]) flash(f"{target['display_name']} es ahora el responsable.", "ok") return redirect(_page(target)) @@ -532,6 +546,7 @@ def transfer_platform(member_id: int): flash("Solo puedes entregar la plataforma a un administrador activo.", "error") return redirect(_page(target)) transfer_ownership(get_db(), g.member["id"], target["id"], "superadmin") + activity.log("chair.superadmin", target["display_name"]) flash(f"{target['display_name']} es ahora el superadministrador. " "Tú eres administrador.", "ok") return redirect(_page(target)) @@ -550,6 +565,9 @@ def erase(member_id: int): # rows back, and nothing can put the pictures back. for stored_name in erase_member(get_db(), member_id): uploads.remove(stored_name) + # After the transaction: a row recording an erasure that rolled back is a + # worse record than no row. + activity.log("member.erased", target["display_name"]) flash(f"{target['display_name']} eliminado. Sus mensajes quedan como «Miembro eliminado».", "ok") return redirect(url_for("members.index")) diff --git a/apps/board/migrations.py b/apps/board/migrations.py index c5709d4..cb04578 100644 --- a/apps/board/migrations.py +++ b/apps/board/migrations.py @@ -313,6 +313,31 @@ def _a_superadmin_above_the_owner(db: sqlite3.Connection) -> None: raise RuntimeError(f"migration left dangling references: {broken}") +def _room_for_identity_and_a_typeface(db: sqlite3.Connection) -> None: + """Columns for the style half's new settings and for the media library. + + Plain ADD COLUMNs — none of these is in a CHECK, an index or a foreign key, + which is what separates this from steps 1, 4 and 7. + + `content_cache.image` is what turns "which post uses this picture?" into a + query. Without it the media library would re-read every post's frontmatter + from the git server on every page view, which is the exact cost that cache + was built to avoid. + + The three new tables — `activity`, `site`, and nothing else — need no step + at all: `CREATE TABLE IF NOT EXISTS` in schema.sql runs before these and + creates them on any database that lacks them. + """ + for table, columns in (("brand", ("typeface", "font_name", "roundness")), + ("content_cache", ("image",))): + existing = _columns(db, table) + if not existing: + continue + for column in columns: + if column not in existing: + db.execute(f"ALTER TABLE {table} ADD COLUMN {column} TEXT") + + # (number, description, function). The number is the value written to # user_version once the step succeeds. STEPS = [ @@ -323,6 +348,8 @@ STEPS = [ (5, "events carry a date of their own", _rooms_for_a_date_of_its_own), (6, "there are no categories any more", _no_more_categories), (7, "a superadministrator above the responsable", _a_superadmin_above_the_owner), + (8, "room for the identity, a typeface and the media library", + _room_for_identity_and_a_typeface), ] diff --git a/apps/board/schema.sql b/apps/board/schema.sql index 15a3491..2e04691 100644 --- a/apps/board/schema.sql +++ b/apps/board/schema.sql @@ -352,9 +352,70 @@ CREATE TABLE IF NOT EXISTS brand ( custom_css TEXT NOT NULL DEFAULT '', logo_name TEXT, favicon_name TEXT, + -- A key from brand.TYPEFACES, or 'propia' when `font_name` holds an uploaded + -- .woff2. Null means the one the site was built with. + typeface TEXT, + font_name TEXT, + -- A key from brand.ROUNDNESS. One setting driving four radius tokens: a site + -- whose cards are round and whose buttons are square looks like two sites. + roundness TEXT, -- Cleared rather than reassigned when that member is erased: the colours -- belong to the association, like an event in the calendar. updated_by INTEGER REFERENCES members(id), updated_at TEXT NOT NULL DEFAULT (datetime('now')), published_at TEXT ); + +-- What somebody did, for the superadministrator to read. +-- +-- An audit trail is the natural companion to a role that can do everything: the +-- question "who made them an administrator?" has no other answer, and asking it +-- after the fact is exactly when nobody can remember. +-- +-- `actor_id` is cleared and not cascaded when that member is erased. That a +-- role was changed is the association's record; whose name was on it is the +-- erased person's data, and the two can be separated. +-- +-- Deliberately not a general event store. One row per act that changes who can +-- do what, or what the public sees — not page views, not sign-ins that worked. +CREATE TABLE IF NOT EXISTS activity ( + id INTEGER PRIMARY KEY, + actor_id INTEGER REFERENCES members(id), + -- A short stable key: 'role.changed', 'member.erased', 'brand.saved'. Stable + -- because it is what a later reader greps for; short because the sentence a + -- person reads is built from it in the template, not stored here in Spanish. + action TEXT NOT NULL, + -- What it was done to, as a display name or a title. A copy on purpose: the + -- row it names may be gone, and "erased Miembro eliminado" is not a record. + object TEXT NOT NULL DEFAULT '', + detail TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); + +CREATE INDEX IF NOT EXISTS activity_recent ON activity(created_at DESC); + +-- The site's identity, as opposed to its look: what it is called, what it says +-- it is, where to find it. One row, pinned like `brand`. +-- +-- Separate from `brand` because the two have different audiences and different +-- failure modes: a wrong colour is ugly, a wrong contact address is a message +-- nobody receives. They are also published to different files. +CREATE TABLE IF NOT EXISTS site ( + id INTEGER PRIMARY KEY CHECK (id = 1), + -- {"es": {"name": …, "tagline": …}, "de": …}: per language, because the + -- tagline is prose and prose is not the same in three languages. + names_json TEXT NOT NULL DEFAULT '{}', + -- {"instagram": "https://…", …} → `sameAs` in the Organization schema, which + -- is how a search or answer engine knows an account and this site are one + -- body. + social_json TEXT NOT NULL DEFAULT '{}', + email TEXT NOT NULL DEFAULT '', + phone TEXT NOT NULL DEFAULT '', + city TEXT NOT NULL DEFAULT '', + street TEXT NOT NULL DEFAULT '', + share_image TEXT NOT NULL DEFAULT '', + footer_text TEXT NOT NULL DEFAULT '', + updated_by INTEGER REFERENCES members(id), + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + published_at TEXT +); diff --git a/apps/board/static/board.css b/apps/board/static/board.css index 5ad5986..9379863 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -816,3 +816,66 @@ input[type="file"] { .btn--danger { background: var(--danger); } .btn--danger:hover { background: var(--danger); filter: brightness(0.9); } + +/* --- the typeface picker ------------------------------------------------ */ + +/* Each option shown in the face it offers. Classes rather than a style + attribute on the label, because the Content-Security-Policy has no + 'unsafe-inline' and style-src falls under default-src: an inline style here + is dropped and all four options render identically, which is a picker that + tells you nothing. The stacks are the ones in brand.TYPEFACES. */ +.face { font-size: 1.05rem; } +.face--sans { font-family: "Montserrat", -apple-system, BlinkMacSystemFont, + "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; } +.face--serif { font-family: Georgia, Cambria, "Times New Roman", Times, serif; } +.face--redonda { font-family: "Trebuchet MS", "Segoe UI", Verdana, sans-serif; } +.face--sistema { font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; } + +/* The font warning. One line closed, which is the point: it is four paragraphs + nobody needs until the moment they are uploading a typeface. */ +.brand-warning { + margin: 0.75rem 0 1.5rem; + border: 1px solid var(--border-light); + border-radius: var(--radius-md); + padding: 0.6rem 0.9rem; + background: var(--surface-soft); +} +.brand-warning summary { cursor: pointer; font-weight: 600; font-size: 0.9rem; } +.brand-warning p { font-size: 0.9rem; color: var(--muted); margin: 0.75rem 0 0; } +.brand-warning p:last-child { margin-bottom: 0.25rem; } + +/* --- the media library -------------------------------------------------- */ + +.media-grid { + list-style: none; + margin: 1rem 0 0; + padding: 0; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 1rem; +} +.media-item { + background: var(--surface); + border: 1px solid var(--border-light); + border-radius: var(--radius-lg); + padding: 0.75rem; +} +/* Orphans are the only rows anybody has to act on, so they say so twice: first + in the order (they sort to the top) and then in the colour. */ +.media-item--orphan { border-color: var(--brand); background: var(--brand-softer); } +.media-item img { + display: block; + width: 100%; + height: 120px; + object-fit: cover; + border-radius: var(--radius-md); + background: var(--surface-soft); +} +.media-item p { margin: 0.4rem 0 0; word-break: break-all; } +.media-item form { margin-top: 0.5rem; } + +/* --- the status screen -------------------------------------------------- */ + +.tag--ok { background: #e4f2e4; color: #1b5e20; } +.tag--warn { background: var(--brand-soft); color: var(--brand-dark); } +.tag--bad { background: #f6dcdc; color: var(--danger); } diff --git a/apps/board/status.py b/apps/board/status.py new file mode 100644 index 0000000..654f30d --- /dev/null +++ b/apps/board/status.py @@ -0,0 +1,191 @@ +"""Estado del sistema — what is actually true of this server right now. + +WordPress calls it Site Health. It earns its place here for a specific reason: +**every outage in this project has been a configuration fact that was invisible +until somebody hit it.** A `CONTENT_TOKEN` with the wrong scope looked exactly +like a working one until an editor pressed save and got a 500. Mail was +unconfigured for a week while invitations were "sent". The settings were right +in `.env.example` and absent from the container. + +So this page asks the questions nobody thinks to ask, and asks them of the +running system rather than of a file: + +* the content token is **exercised**, not merely checked for emptiness — the + single most valuable line here, because "present" was never the problem +* the mail host is resolved and connected to +* the newest backup, with its age and size +* free disk, which is the one that ends everything at once +* every setting `.env.example` documents that the container does not have + +**It changes nothing.** No buttons, no fixes, no restarts — a page that answers +questions. That is deliberate: a diagnostic screen that can also act is a screen +somebody uses to act without reading, and the actions here are the ones with the +longest reach on the box. +""" + +from __future__ import annotations + +import os +import shutil +import smtplib +import socket +from datetime import datetime, timezone +from pathlib import Path + +from flask import Blueprint, current_app, render_template + +from . import gitea, mail, uploads +from .db import get_db +from .security import superadmin_required + +bp = Blueprint("status", __name__) + +# Where deploy-board.sh puts them. Read-only, and missing is an answer. +BACKUP_DIR = "/srv/board/backups" + +# Settings whose absence turns a feature off rather than breaking the app. The +# names are the ones in infra/board/.env.example; the sentence is what stops +# working. Checked against os.environ because the container cannot read +# /srv/board/.env — compose substitutes it in and the file never arrives. +EXPECTED = ( + ("BOARD_SECRET_KEY", "las sesiones (sin esto la app no arranca)"), + ("CONTENT_TOKEN", "publicar en el sitio: el editor y la marca"), + ("MAIL_HOST", "invitaciones y recuperar contraseña"), + ("MAIL_USER", "autenticarse en el servidor de correo"), + ("MAIL_PASSWORD", "autenticarse en el servidor de correo"), + ("BOARD_OWNER", "sembrar al superadministrador en el primer arranque"), + ("GITEA_URL", "hablar con el servidor de git"), + ("CONTENT_REPO", "saber en qué repositorio se publica"), +) + + +def _ok(label, detail=""): + return {"state": "ok", "label": label, "detail": detail} + + +def _warn(label, detail=""): + return {"state": "warn", "label": label, "detail": detail} + + +def _bad(label, detail=""): + return {"state": "bad", "label": label, "detail": detail} + + +def _content_token() -> dict: + """Not "is it set" — "does it work". + + A token with `admin` scope and no `repository` scope is present, non-empty, + and cannot write a single file; that exact configuration broke publishing + for three phases while every check anybody thought to run said it was fine. + So this one reads the content directory through the API and reports what + came back. + """ + try: + token = gitea.content_token() + except gitea.GiteaError as exc: + return _bad("No hay token para publicar", str(exc)) + + which = "CONTENT_TOKEN" if os.environ.get("CONTENT_TOKEN") else "GITEA_ADMIN_TOKEN" + try: + gitea.list_directory("content/post", token) + except gitea.GiteaError as exc: + return _bad(f"El token ({which}) no puede leer el repositorio", str(exc)) + except OSError as exc: + return _warn("No se pudo contactar con el servidor de git", str(exc)) + + if which == "GITEA_ADMIN_TOKEN": + return _warn( + "Publicando con el token de administración", + "Funciona, pero ese token puede modificar cualquier cuenta del " + "servidor de git. Crea uno con permiso de repositorio y ponlo en " + "CONTENT_TOKEN.") + return _ok("El token de publicación funciona", f"{which}, con acceso de lectura") + + +def _mail() -> dict: + if not mail.configured(): + return _warn("Sin correo saliente", + "Nadie puede ser invitado ni recuperar su contraseña.") + host = current_app.config["MAIL_HOST"] + port = int(current_app.config["MAIL_PORT"] or 587) + try: + with smtplib.SMTP(host, port, timeout=5) as server: + server.ehlo() + except (OSError, smtplib.SMTPException) as exc: + return _bad(f"{host}:{port} no responde", str(exc)) + return _ok(f"{host}:{port} responde", "La conexión se abre; no se envía nada.") + + +def _backups() -> dict: + folder = Path(BACKUP_DIR) + if not folder.is_dir(): + return _warn("No hay carpeta de copias", f"{BACKUP_DIR} no existe.") + files = sorted(folder.glob("board-*.db.gz"), key=lambda f: f.stat().st_mtime) + if not files: + return _bad("Ninguna copia de seguridad", f"{BACKUP_DIR} está vacía.") + newest = files[-1] + age = datetime.now(timezone.utc) - datetime.fromtimestamp( + newest.stat().st_mtime, timezone.utc) + size = newest.stat().st_size // 1024 + detail = f"{newest.name}, {size} KB, {len(files)} en total" + if age.days >= 2: + return _warn(f"La copia más reciente tiene {age.days} días", detail) + return _ok("Copia reciente", detail) + + +def _disk() -> dict: + """The one that ends everything at once, and silently: SQLite cannot write, + uploads fail, and the log that would say so cannot be written either.""" + # Through `uploads.directory()`, which creates it: asking statvfs about a + # path that does not exist raises, and "the uploads folder has not been made + # yet" is not a disk problem. + usage = shutil.disk_usage(uploads.directory()) + free_mb = usage.free // (1024 * 1024) + detail = f"{free_mb} MB libres de {usage.total // (1024 * 1024)} MB" + if free_mb < 200: + return _bad("Queda muy poco disco", detail) + if free_mb < 1000: + return _warn("Queda poco disco", detail) + return _ok("Disco suficiente", detail) + + +def _settings() -> dict: + missing = [(name, why) for name, why in EXPECTED if not os.environ.get(name)] + if not missing: + return _ok("Todos los ajustes esperados están puestos") + return _warn( + f"{len(missing)} ajuste{'s' if len(missing) > 1 else ''} sin poner", + "; ".join(f"{name} — {why}" for name, why in missing)) + + +def _counts() -> dict: + db = get_db() + one = lambda sql: db.execute(sql).fetchone()[0] # noqa: E731 + return { + "members": one("SELECT COUNT(*) FROM members WHERE role != 'tombstone'"), + "admins": one("SELECT COUNT(*) FROM members WHERE role IN " + "('superadmin', 'owner', 'admin', 'moderator')"), + # `role != 'tombstone'` because the row erased members are reassigned + # to is inactive by construction and is not a suspended person. + "suspended": one("SELECT COUNT(*) FROM members " + "WHERE active = 0 AND role != 'tombstone'"), + "threads": one("SELECT COUNT(*) FROM threads WHERE deleted_at IS NULL"), + "pending": one("SELECT COUNT(*) FROM submissions WHERE state = 'pending'"), + "events": one("SELECT COUNT(*) FROM events"), + "posts": one("SELECT COUNT(*) FROM content_cache WHERE generated = 0"), + } + + +@bp.route("/gestion/estado") +@superadmin_required +def index(): + checks = [ + ("Publicar en el sitio", _content_token()), + ("Correo saliente", _mail()), + ("Copias de seguridad", _backups()), + ("Disco", _disk()), + ("Ajustes del contenedor", _settings()), + ] + return render_template("status.html", checks=checks, counts=_counts(), + worst=min((c[1]["state"] for c in checks), + key=["bad", "warn", "ok"].index)) diff --git a/apps/board/submissions.py b/apps/board/submissions.py index af5d512..1fcbf9b 100644 --- a/apps/board/submissions.py +++ b/apps/board/submissions.py @@ -30,7 +30,7 @@ from datetime import date as date_type from flask import (Blueprint, abort, current_app, flash, g, redirect, render_template, request, send_from_directory, url_for) -from . import content, gitea, uploads +from . import activity, content, gitea, uploads from .db import get_db from .render import excerpt, to_html from .security import is_at_least, login_required, moderator_required @@ -360,6 +360,7 @@ def approve(submission_id: int): # in one place, and no orphan in /data/uploads that nothing will ever serve. if row["photo_name"]: uploads.remove(row["photo_name"]) + activity.log("submission.approved", row["title"], f"de {row['author']}") flash(f"Publicado «{row['title']}». La traducción tarda un par de minutos.", "ok") return redirect(url_for("submissions.index")) @@ -387,6 +388,7 @@ def reject(submission_id: int): WHERE id = ?""", (note, g.member["id"], submission_id), ) + activity.log("submission.rejected", row["title"], f"de {row['author']}") flash("Devuelto al autor con tu motivo.", "ok") return redirect(url_for("submissions.index")) diff --git a/apps/board/templates/activity.html b/apps/board/templates/activity.html new file mode 100644 index 0000000..d894fa4 --- /dev/null +++ b/apps/board/templates/activity.html @@ -0,0 +1,51 @@ +{# Gestión → Registro de actividad. Read-only by construction: there is nothing + here to press, because an audit trail you can edit is not one. #} +{% extends "base.html" %} +{% block title %}Registro{% endblock %} + +{% block main %} +
+

Registro de actividad

+ Volver a Gestión +
+ +

+ Lo que se ha hecho que cambia quién puede hacer qué, o qué ve el público. No + están las visitas ni los inicios de sesión correctos: un registro que lo + apunta todo es un registro que nadie lee. +

+ +{% if not rows %} +

Todavía no hay nada apuntado.

+{% else %} + + + + {% for row in rows %} + + + + + + {% endfor %} + +
CuándoQuiénQué
{{ row.at }} + {# A name that is simply gone, rather than a tombstone: the row stays + when somebody is erased and the name does not, which is the whole + arrangement. #} + {{ row.actor or 'Alguien que ya no está' }} + + {{ row.sentence }} + {% if row.detail %} · {{ row.detail }}{% endif %} +
+ +
+ {% if page > 0 %} + ← Más reciente + {% endif %} + {% if more %} + Más antiguo → + {% endif %} +
+{% endif %} +{% endblock %} diff --git a/apps/board/templates/base.html b/apps/board/templates/base.html index 46079d5..df9faa4 100644 --- a/apps/board/templates/base.html +++ b/apps/board/templates/base.html @@ -80,7 +80,7 @@ Publicaciones{% set waiting = pending_review() %}{% if waiting %} {{ waiting }}{% endif %}
  • Calendario
  • - {% if g.member.role in ('owner', 'admin') %} + {% if is_at_least(g.member.role, 'admin') %}
  • Gestión
  • {% endif %} diff --git a/apps/board/templates/brand_form.html b/apps/board/templates/brand_form.html index aefb4a0..311232a 100644 --- a/apps/board/templates/brand_form.html +++ b/apps/board/templates/brand_form.html @@ -108,6 +108,97 @@ {% endif %} +

    Tipografía

    +

    + Las cuatro primeras ya están en el ordenador de quien lee: no se descarga + nada de ningún sitio. Eso es a propósito — una hoja de estilos que pide una + fuente a Google le cuenta a Google la dirección IP de todo el que entra, y + eso no se puede consentir en nombre de quien visita la página. +

    + +
    + {% for key, (label, stack) in typefaces.items() %} + + {% endfor %} + +
    + + {% if state.font_name %} +

    Ya hay una tipografía subida. Si eliges otra, la sustituye.

    + {% endif %} + + + + {# Closed by default and one line tall, as asked. Everything in it is a way + this goes wrong in practice rather than in theory. #} +
    + Antes de subir una tipografía, lee esto + +

    Lo que hace una fuente mala. Una tipografía sin + ñ á ü ç ã dibuja esas letras con otra distinta, así + que el español y el portugués salen visiblemente remendados — y nadie te + avisa. Un archivo de 2 MB retrasa cada página en un móvil. Una fuente de + titulares puesta a 16px no se lee.

    + +

    Cómo hacerlo bien. Sube un solo archivo, el peso normal: + la negrita y la cursiva las fabrica el navegador a partir de él, lo cual + está bien para un sitio con logotipo y mal para textos largos. Subconjunta + la fuente a latín y latín extendido-A. Que no pase de unos 100 KB. Sólo + .woff2: es el formato de la web, lo entienden + todos los navegadores y es el que este formulario comprueba por su firma, + no por el nombre del archivo. Antes de guardar, mira cómo quedan + ñ á ü ç ã en la vista previa de arriba.

    + +

    La licencia, que es lo único de aquí que cuesta dinero. + Una tipografía es software, y una licencia de escritorio no es una licencia + web: servir desde tu propio servidor una fuente que compraste para el + ordenador suele incumplirla, y esa responsabilidad viaja con la plataforma + a cada organización donde la instales. Busca + SIL OFL o Apache 2.0: las dos permiten + alojarla uno mismo y redistribuirla.

    + +

    Dónde buscarlas sin riesgo. + Google Fonts + (descargándolas, no enlazándolas, por lo del párrafo primero), + Fontsource + (las mismas familias ya empaquetadas en .woff2), + Font Squirrel, + The League of Moveable Type, + Velvetyne, + Open Foundry y + Use & Modify. + Comprueba la licencia del archivo que te has descargado, no la de la página + desde la que llegaste a él.

    +
    + +

    Esquinas

    +

    + Lo redondeadas que son las tarjetas, los botones y las fotos. Un solo ajuste + para todo: un sitio con tarjetas redondas y botones cuadrados parece dos + sitios. +

    +
    + {% for key, (label, values) in roundness.items() %} + + {% endfor %} +
    +
    Avanzado diff --git a/apps/board/templates/gestion.html b/apps/board/templates/gestion.html index ad7a866..a89080d 100644 --- a/apps/board/templates/gestion.html +++ b/apps/board/templates/gestion.html @@ -53,6 +53,17 @@

    +
    +
    +

    Biblioteca de medios

    + Abrir +
    +

    + Todas las imágenes del sitio público y qué artículo usa cada una. Las que + no usa nadie —de artículos que se borraron— se pueden quitar desde ahí. +

    +
    + {% if g.member.role == 'superadmin' %}
    @@ -68,6 +79,42 @@ volver a lo de fábrica.

    + +
    +
    +

    Identidad

    + Abrir +
    + {% set site = identity() %}{% if site.updated_at and not site.published_at %} +

    Hay cambios guardados que no han llegado al sitio público.

    + {% endif %} +

    + El nombre y el lema en los tres idiomas, los perfiles de la asociación en + otros sitios, el contacto y el pie de página. +

    +
    + +
    +
    +

    Estado del sistema

    + Abrir +
    +

    + Si el token para publicar funciona de verdad, si el correo sale, cuándo fue + la última copia de seguridad y cuánto disco queda. No cambia nada: responde. +

    +
    + +
    +
    +

    Registro de actividad

    + Abrir +
    +

    + Quién cambió un rol, aprobó una publicación, tocó el aspecto del sitio o + eliminó a alguien. +

    +
    {% endif %} {% if counts.pending %} diff --git a/apps/board/templates/identity_form.html b/apps/board/templates/identity_form.html new file mode 100644 index 0000000..f10ff5d --- /dev/null +++ b/apps/board/templates/identity_form.html @@ -0,0 +1,112 @@ +{# Gestión → Identidad: what the site is called and where to find it. + + Everything here used to be in config.yaml, which meant it could only be + changed by somebody with the repository. The fields show their current value + as a placeholder rather than as a value, deliberately: a form prefilled with + the fallback saves the fallback the first time anybody presses the button, + and the default is frozen from then on. #} +{% extends "base.html" %} +{% block title %}Identidad{% endblock %} + +{% block main %} +
    +

    Identidad

    + Volver a Gestión +
    + +

    + Cómo se llama el sitio, qué dice que es y dónde encontrarlo. Lo de aquí + alimenta también los datos estructurados: es lo que lee un buscador —o una IA + que responde preguntas— para saber que esta asociación y esas cuentas son el + mismo cuerpo. +

    + +{% if state.updated_at and not state.published_at %} +
    +

    Pendiente de publicar

    +

    + Guardado aquí, pero no ha llegado al sitio público: no se pudo contactar + con el servidor de git la última vez. +

    +
    + + +
    +
    +{% endif %} + +
    + + +

    Nombre y lema

    +

    + Uno por idioma. El lema es la frase que sale al compartir un enlace, la que + describe al sitio en los buscadores y la primera línea de + llms.txt. Déjalo vacío para no cambiar lo que hay. +

    + + {% for code, label, _name, _tagline in languages %} +
    + {{ label }} + + + + + +
    + {% endfor %} + +

    Perfiles

    +

    + Las cuentas de la asociación en otros sitios. Salen en el pie de página y + como sameAs en los datos estructurados, que es + como un buscador sabe que esa cuenta de Instagram y esta web son lo mismo. +

    + {% for key, label, placeholder in networks %} + + + {% endfor %} + +

    Contacto y lugar

    +

    + Público, y pensado para que lo lea una persona tanto como un buscador: una + dirección y una ciudad son lo que pone a una asociación en un resultado + local y no sólo en uno web. +

    + + + + + + + + + + + + +

    Al compartir, y el pie

    + + +

    + La que sale al compartir un artículo que no tiene foto propia. Si la dejas + vacía se usa el logotipo, que casi siempre es lo que quieres: esto es para + cuando prefieres otra cosa —una foto de la ciudad, por ejemplo. +

    + + + +

    Si lo dejas vacío, el pie pone el nombre y el año.

    + + +
    +{% endblock %} diff --git a/apps/board/templates/media.html b/apps/board/templates/media.html new file mode 100644 index 0000000..1945696 --- /dev/null +++ b/apps/board/templates/media.html @@ -0,0 +1,47 @@ +{# Gestión → Biblioteca de medios. + + Orphans first, because they are the only rows anybody has to act on: a + listing sorted by name buries them among the pictures doing their job, which + is how they went unnoticed for the life of the site. #} +{% extends "base.html" %} +{% block title %}Medios{% endblock %} + +{% block main %} +
    +

    Biblioteca de medios

    + Volver a Gestión +
    + +

    + Todas las imágenes que lleva el sitio público, y qué artículo usa cada una. + {% if orphans %} + {{ orphans }} no la usa nadie: se subieron con un artículo que + luego se borró, y siguen ahí ocupando sitio. + {% endif %} +

    + +{% if not items %} +

    No hay imágenes todavía.

    +{% else %} +
      + {% for item in items %} +
    • + +

      {{ item.name }}

      +

      {{ item.size }} KB

      + {% if item.posts %} +

      {{ item.posts|join(', ') }}

      + {% else %} +

      No la usa ningún artículo.

      +
      + + + +
      + {% endif %} +
    • + {% endfor %} +
    +{% endif %} +{% endblock %} diff --git a/apps/board/templates/member.html b/apps/board/templates/member.html index b5b28af..f48a97b 100644 --- a/apps/board/templates/member.html +++ b/apps/board/templates/member.html @@ -19,7 +19,7 @@ cannot offer a role that comes back 403. #} {% set is_super = me.role == 'superadmin' %} {% set is_chair = me.role in ('superadmin', 'owner') %} -{% set is_admin = me.role in ('superadmin', 'owner', 'admin') %} +{% set is_admin = is_at_least(me.role, 'admin') %} {% set can_assign = assignable_roles(me.role) %} {% block main %} diff --git a/apps/board/templates/members.html b/apps/board/templates/members.html index 4a90610..5f0fd80 100644 --- a/apps/board/templates/members.html +++ b/apps/board/templates/members.html @@ -2,7 +2,7 @@ {% block title %}Miembros{% endblock %} {% set me = g.member %} -{% set is_admin = me.role in ('owner', 'admin') %} +{% set is_admin = is_at_least(me.role, 'admin') %} {% block main %}
    diff --git a/apps/board/templates/status.html b/apps/board/templates/status.html new file mode 100644 index 0000000..6a3cc5c --- /dev/null +++ b/apps/board/templates/status.html @@ -0,0 +1,49 @@ +{# Gestión → Estado del sistema. + + Nothing on this page changes anything, deliberately: a diagnostic screen that + can also act is a screen somebody uses to act without reading, and the actions + it would offer are the ones with the longest reach on this box. #} +{% extends "base.html" %} +{% block title %}Estado{% endblock %} + +{% block main %} +
    +

    Estado del sistema

    + Volver a Gestión +
    + +

    + Lo que es verdad del servidor ahora mismo, preguntado al sistema y no a un + archivo. Esta página no cambia nada: sólo responde. +

    + +{% if worst == 'ok' %} +

    Todo responde.

    +{% endif %} + +{% for title, check in checks %} +
    +
    +

    {{ title }}

    + + {{ {'ok': 'Bien', 'warn': 'Atención', 'bad': 'Mal'}[check.state] }} + +
    +

    {{ check.label }}

    + {% if check.detail %}

    {{ check.detail }}

    {% endif %} +
    +{% endfor %} + +
    +

    Cuántas cosas hay

    +

    + {{ counts.members }} miembros · {{ counts.admins }} con algún cargo + {% if counts.suspended %} · {{ counts.suspended }} suspendido{{ '' if counts.suspended == 1 else 's' }}{% endif %} +

    +

    + {{ counts.posts }} artículos publicados · {{ counts.threads }} hilos en el muro · + {{ counts.events }} eventos en el calendario + {% if counts.pending %} · {{ counts.pending }} propuesta{{ '' if counts.pending == 1 else 's' }} esperando{% endif %} +

    +
    +{% endblock %} diff --git a/apps/board/tests/test_brand.py b/apps/board/tests/test_brand.py index 127fe14..f1bc8a1 100644 --- a/apps/board/tests/test_brand.py +++ b/apps/board/tests/test_brand.py @@ -393,3 +393,116 @@ def test_erasing_whoever_set_the_brand_leaves_it_standing(client, db, post, admi row = db.execute("SELECT tokens_json, updated_by FROM brand").fetchone() assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"} assert row["updated_by"] is None + + +# --- the typeface and the corners ----------------------------------------- + +WOFF2 = b"wOF2" + b"\x00" * 200 +TTF = b"\x00\x01\x00\x00" + b"\x00" * 200 + + +def test_a_preset_typeface_reaches_the_stylesheet(client, post, admin): + save(post, typeface="serif") + + css = client.get("/comunidad/marca.css").get_data(as_text=True) + + assert "body { font-family: Georgia" in css + assert "@font-face" not in css # nothing is downloaded for a preset + + +def test_the_default_typeface_writes_no_rule_at_all(client, post, admin): + """An install that has not touched this serves what it always served.""" + save(post, typeface="sans") + + css = client.get("/comunidad/marca.css").get_data(as_text=True) + + assert "font-family" not in css + + +def test_a_font_that_is_not_a_woff2_is_refused(client, db, post, admin): + """By its signature, not its name — the same rule every other upload here + follows. A .ttf renders fine in a browser and is two to five times the size + for the same letters.""" + response = save(post, typeface="propia", font=(io.BytesIO(TTF), "bonita.woff2"), + content_type="multipart/form-data", follow_redirects=True) + + assert "no es un .woff2" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_an_enormous_font_is_refused(client, db, post, admin): + big = b"wOF2" + b"\x00" * 500_000 + response = save(post, typeface="propia", font=(io.BytesIO(big), "gorda.woff2"), + content_type="multipart/form-data", follow_redirects=True) + + assert "Subconjunta" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_choosing_propia_without_a_file_is_refused(client, db, post, admin): + """Rather than falling back silently: the site would look unchanged and the + setting would say otherwise.""" + response = save(post, typeface="propia", follow_redirects=True) + + assert "hay que subir un archivo" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_an_uploaded_font_is_declared_served_and_falls_back(client, db, post, admin): + save(post, typeface="propia", font=(io.BytesIO(WOFF2), "bonita.woff2"), + content_type="multipart/form-data") + + name = db.execute("SELECT font_name FROM brand").fetchone()["font_name"] + css = client.get("/comunidad/marca.css").get_data(as_text=True) + + assert "@font-face" in css and name in css + # Named first, with the old stack behind it: a font that 404s or arrives + # corrupt must leave a readable site, not a browser default. + assert 'body { font-family: "VLPropia", "Montserrat"' in css + + served = client.get(f"/comunidad/marca/{name}") + assert served.status_code == 200 + assert served.mimetype == "font/woff2" + + +def test_roundness_writes_the_four_radius_tokens(client, post, admin): + save(post, roundness="recta") + + css = client.get("/comunidad/marca.css").get_data(as_text=True) + + for token in ("--radius-xl", "--radius-lg", "--radius-md", "--radius-sm"): + assert f"{token}: 0;" in css, token + + +def test_a_made_up_choice_falls_back_rather_than_being_stored(client, db, post, admin): + """Both pickers read a key from a table in this module, never the value that + arrived.""" + save(post, typeface="../../etc/passwd", roundness="DROP TABLE brand") + + row = db.execute("SELECT typeface, roundness FROM brand").fetchone() + assert (row["typeface"], row["roundness"]) == ("sans", "suave") + + +def test_restoring_takes_the_font_with_it(app, client, db, post, admin): + save(post, typeface="propia", font=(io.BytesIO(WOFF2), "bonita.woff2"), + content_type="multipart/form-data") + name = db.execute("SELECT font_name FROM brand").fetchone()["font_name"] + + post("/comunidad/gestion/marca/restaurar") + + with app.app_context(): + from apps.board import uploads + assert not uploads.directory().joinpath(name).exists() + assert "font-family" not in client.get("/comunidad/marca.css").get_data(as_text=True) + + +def test_the_font_and_the_radii_reach_the_public_site(db, post, admin, repo): + save(post, typeface="propia", roundness="redonda", + font=(io.BytesIO(WOFF2), "bonita.woff2"), + content_type="multipart/form-data") + + assert "static/brand/font.woff2" in repo.files + yaml = repo.files["data/brand.yaml"].decode("utf-8") + assert 'font: "/brand/font.woff2"' in yaml + assert "font_stack: '\"VLPropia\"" in yaml + assert ' radius-xl: "28px"' in yaml diff --git a/apps/board/tests/test_navigation.py b/apps/board/tests/test_navigation.py index d3ce9f2..14776bc 100644 --- a/apps/board/tests/test_navigation.py +++ b/apps/board/tests/test_navigation.py @@ -217,3 +217,40 @@ def test_signing_in_sets_the_hint_and_signing_out_clears_it(client, db, post, ma signed_out = post("/comunidad/logout") assert any("vl_sesion=;" in header or "vl_sesion=\"\"" in header for header in signed_out.headers.get_all("Set-Cookie")) + + +# --- the tier above admin ------------------------------------------------- + +def test_the_superadmin_sees_gestion(nav, superadmin_id): + """The regression this file exists for, one tier higher. + + `base.html` asked `g.member.role in ('owner', 'admin')`, which was right + until a role appeared above both — and then Gestión vanished from the + navigation of the one account that owns every screen on it. 622 tests + passed while it was broken, because every one of them signed in as an + admin or below. + """ + body = nav(superadmin_id) + assert "Gestión" in body + assert "/comunidad/gestion" in body + + +@pytest.mark.parametrize("role", ["superadmin", "owner", "admin"]) +def test_gestion_opens_for_every_role_that_can_see_it(role, client, db, + superadmin_id, make_member, + sign_in): + """Seeing the link and reaching the page are two different checks, and a + role that passes one and fails the other is the worst of both.""" + member_id = superadmin_id if role == "superadmin" else make_member("x", role=role) + sign_in(member_id) + assert client.get("/comunidad/gestion").status_code == 200 + + +def test_the_public_strip_offers_gestion_to_the_superadmin(client, superadmin_id, + sign_in): + """`sesion.json` draws the bar on vienalatina.com from its own list, so it + is a second place the same rule can be got wrong.""" + sign_in(superadmin_id) + labels = [s["label"] for s in + client.get("/comunidad/sesion.json").get_json()["sections"]] + assert "Gestión" in labels diff --git a/apps/board/tests/test_tools.py b/apps/board/tests/test_tools.py new file mode 100644 index 0000000..5634f23 --- /dev/null +++ b/apps/board/tests/test_tools.py @@ -0,0 +1,260 @@ +"""The three screens the superadministrator gets, and the identity half. + +Grouped in one file because they are one phase and share one question: who may +open this, and does it tell the truth about the running system. +""" + +from __future__ import annotations + +import json + +import pytest + +from apps.board import activity, identity + +SCREENS = { + "/comunidad/gestion/identidad": "superadmin", + "/comunidad/gestion/estado": "superadmin", + "/comunidad/gestion/registro": "superadmin", + "/comunidad/gestion/medios": "admin", +} + + +@pytest.fixture +def boss(superadmin_id, sign_in): + sign_in(superadmin_id) + return superadmin_id + + +@pytest.mark.parametrize("url", sorted(SCREENS)) +def test_every_screen_opens_for_the_superadmin(client, boss, url, repo): + assert client.get(url).status_code == 200 + + +@pytest.mark.parametrize("url,needs", sorted(SCREENS.items())) +def test_each_screen_refuses_the_roles_below_it(client, make_member, sign_in, + url, needs, repo): + """Medios is open to admins — they are the people who upload, and the worst + an admin can do there is remove a picture from a post they could already + have edited. The other three are the platform's.""" + # Everything above the rank passes too, which is what `is_at_least` means. + allowed = {"superadmin": set(), "admin": {"admin", "owner"}}[needs] + for role in ("user", "moderator", "admin", "owner"): + sign_in(make_member(f"persona-{role}", role=role)) + expected = 200 if role in allowed else 403 + assert client.get(url).status_code == expected, (url, role) + + +# --- identity ------------------------------------------------------------- + +def test_the_identity_round_trips_all_three_languages(client, db, post, boss, repo): + post("/comunidad/gestion/identidad", { + "name-es": "Viena Latina", "tagline-es": "La comunidad en Viena.", + "name-de": "Wien Latina", "tagline-de": "Die Community in Wien.", + "tagline-pt-br": "A comunidade em Viena.", + "social-instagram": "https://instagram.com/vienalatina", + "email": "hola@vienalatina.com", "city": "Wien", + "footer_text": "Asociación Viena Latina", + }) + + body = client.get("/comunidad/gestion/identidad").get_data(as_text=True) + for value in ("Wien Latina", "Die Community in Wien.", + "A comunidade em Viena.", "https://instagram.com/vienalatina", + "hola@vienalatina.com", "Asociación Viena Latina"): + assert value in body, value + + +def test_an_untouched_language_is_not_written_at_all(client, db, post, boss, repo): + """A file repeating config.yaml's own values back at it would make the + fallback meaningless and freeze today's defaults for good.""" + post("/comunidad/gestion/identidad", {"tagline-es": "Sólo esto."}) + + names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0]) + assert names == {"es": {"name": "", "tagline": "Sólo esto."}} + yaml = repo.files["data/site.yaml"].decode("utf-8") + assert "de:" not in yaml and "pt-br:" not in yaml + + +def test_a_social_link_that_is_not_https_is_refused(client, db, post, boss, repo): + """These render in the footer of every public page. `javascript:` in an href + is a script running on vienalatina.com.""" + response = post("/comunidad/gestion/identidad", + {"social-instagram": "javascript:alert(1)"}, + follow_redirects=True) + + assert "tiene que empezar por https" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM site").fetchone()["n"] == 0 + + +def test_a_tagline_is_flattened_to_one_line(client, db, post, boss, repo): + """A newline inside og:description is a share card that renders raggedly in + some readers and truncated in others.""" + post("/comunidad/gestion/identidad", {"tagline-es": "Una línea.\n\nY otra."}) + + names = json.loads(db.execute("SELECT names_json FROM site").fetchone()[0]) + assert names["es"]["tagline"] == "Una línea. Y otra." + + +def test_the_yaml_is_what_hugo_reads(client, post, boss, repo): + post("/comunidad/gestion/identidad", { + "name-es": "Viena Latina", "tagline-es": "La comunidad.", + "social-instagram": "https://instagram.com/vl", + "social-bluesky": "https://bsky.app/profile/vl", + "email": "hola@vienalatina.com", "city": "Wien", + }) + + yaml = repo.files["data/site.yaml"].decode("utf-8") + assert ' name: "Viena Latina"' in yaml + assert ' tagline: "La comunidad."' in yaml + # sameAs is a flat list of URLs: the names of the networks appear nowhere in + # the schema, only the addresses. + assert 'sameAs:\n - "https://instagram.com/vl"' in yaml + assert 'email: "hola@vienalatina.com"' in yaml + + +def test_a_quote_in_a_name_cannot_break_the_file(client, post, boss, repo): + post("/comunidad/gestion/identidad", {"name-es": 'Viena "La" Latina\\'}) + + yaml = repo.files["data/site.yaml"].decode("utf-8") + assert r'name: "Viena \"La\" Latina\\"' in yaml + + +# --- the activity log ----------------------------------------------------- + +def test_the_acts_that_change_power_are_recorded(client, db, post, boss, make_member): + maria = make_member("maria") + post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"}) + post(f"/comunidad/miembros/{maria}/estado", {"active": "0"}) + + rows = db.execute( + "SELECT action, object, detail FROM activity ORDER BY id").fetchall() + + assert [(r["action"], r["object"]) for r in rows] == [ + ("role.changed", "Maria"), ("member.suspended", "Maria")] + assert "Miembro → Moderador" in rows[0]["detail"] + + +def test_the_log_survives_the_person_who_wrote_it(client, db, post, boss, make_member): + """The row stays and the name goes. That a role was changed is the + association's record; whose name was on it is the erased person's data.""" + admin_id = make_member("admina", role="admin") + maria = make_member("maria") + sign_in_as = client.session_transaction + with sign_in_as() as session: + session["member_id"] = admin_id + session["csrf"] = "token-for-tests" + post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"}) + + with sign_in_as() as session: + session["member_id"] = boss + post(f"/comunidad/miembros/{admin_id}/eliminar") + + rows = db.execute("SELECT actor_id, action FROM activity " + "WHERE action = 'role.changed'").fetchall() + assert len(rows) == 1 + assert rows[0]["actor_id"] is None + + +def test_a_broken_log_does_not_break_the_thing_it_records(app, db, boss, + make_member, monkeypatch): + """An administrator who could not be appointed because the note about it + could not be saved is a worse outcome than a gap in the notes.""" + with app.test_request_context(): + monkeypatch.setattr(activity, "get_db", + lambda: (_ for _ in ()).throw(RuntimeError("no"))) + activity.log("role.changed", "Maria") # must not raise + + +def test_the_registro_reads_as_sentences(client, db, post, boss, make_member): + maria = make_member("maria") + post(f"/comunidad/miembros/{maria}/rol", {"role": "moderator"}) + + body = client.get("/comunidad/gestion/registro").get_data(as_text=True) + + assert "cambió el rol de Maria" in body + + +# --- the media library ---------------------------------------------------- + +def test_an_orphan_is_named_as_one_and_a_used_picture_is_not(client, db, boss, repo): + repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff" + repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff" + db.execute("""INSERT INTO content_cache (path, sha, title, date, image) + VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01', + '/uploads/usada-aaaaaa.jpg')""") + + body = client.get("/comunidad/gestion/medios").get_data(as_text=True) + + assert "1 no la usa nadie" in body + assert "Un artículo" in body + # And the orphan is first, because it is the only row anybody has to act on. + assert body.index("huerfana-bbbbbb") < body.index("usada-aaaaaa") + + +def test_a_picture_in_use_cannot_be_deleted(client, db, post, boss, repo): + repo.files["static/uploads/usada-aaaaaa.jpg"] = b"\xff\xd8\xff" + db.execute("""INSERT INTO content_cache (path, sha, title, date, image) + VALUES ('content/post/x.es.md', 'a', 'Un artículo', '2026-01-01', + '/uploads/usada-aaaaaa.jpg')""") + + response = post("/comunidad/gestion/medios/usada-aaaaaa.jpg/eliminar", + follow_redirects=True) + + assert "está en uso" in response.get_data(as_text=True) + assert "static/uploads/usada-aaaaaa.jpg" in repo.files + + +def test_an_orphan_is_deleted_and_logged(client, db, post, boss, repo): + repo.files["static/uploads/huerfana-bbbbbb.jpg"] = b"\xff\xd8\xff" + + post("/comunidad/gestion/medios/huerfana-bbbbbb.jpg/eliminar", + {"sha": repo._sha(b"\xff\xd8\xff")}) + + assert "static/uploads/huerfana-bbbbbb.jpg" not in repo.files + assert db.execute("SELECT action, object FROM activity").fetchone()["object"] == \ + "huerfana-bbbbbb.jpg" + + +def test_the_editor_records_which_picture_a_post_uses(client, repo, db, post, + superadmin_id, sign_in): + """Which is what makes "does anything use this?" a query rather than a + re-read of every post's frontmatter from the git server. + + The cache is filled by the listing rather than by the write — it is keyed on + the sha the git server reports — so opening Contenido is the step that puts + the row there.""" + sign_in(superadmin_id) + post("/comunidad/contenido/post/nuevo", + {"title": "Con foto", "body": "Texto.", "date": "2026-10-03", + "image": "/uploads/foto-abcdef.jpg"}) + client.get("/comunidad/contenido/post") + + row = db.execute("SELECT image FROM content_cache").fetchone() + assert row["image"] == "/uploads/foto-abcdef.jpg" + + +# --- the status screen ---------------------------------------------------- + +def test_the_status_screen_says_when_the_token_cannot_write(client, boss, monkeypatch): + """"Present" was never the problem. A token with the wrong scope is + non-empty, looks fine, and cannot write a single file — which is exactly the + configuration that broke publishing for three phases.""" + from apps.board import gitea, status + monkeypatch.setattr(status.gitea, "list_directory", + lambda *a, **k: (_ for _ in ()).throw( + gitea.GiteaError("403: sin permiso de repositorio"))) + + body = client.get("/comunidad/gestion/estado").get_data(as_text=True) + + assert "no puede leer el repositorio" in body + assert "sin permiso de repositorio" in body + + +def test_the_status_screen_counts_what_is_there(client, db, boss, make_member, repo): + make_member("maria") + make_member("luisa", role="moderator") + + body = client.get("/comunidad/gestion/estado").get_data(as_text=True) + + assert "3 miembros" in body # the superadministrator and the two + assert "2 con algún cargo" in body # superadministrator + moderator diff --git a/docs/server-setup.md b/docs/server-setup.md index 4e7cab7..f7f7dde 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -1045,7 +1045,7 @@ Choosing a picture shows a thumbnail with its name and size before anything is uploaded. That is the one reason `blob:` is in the `img-src` policy — a handle to bytes already in the page, which reaches no network. -### 11.18 Marca: the admin owns the look +### 11.18 Marca: the superadministrator owns the look *Gestión* → **Marca**, admins only. Colours, a logo and a favicon for both halves of the site, with an *Avanzado* fold holding every token as a text field @@ -1099,6 +1099,21 @@ block is where they see them, restyled by `board.js` setting the custom properties on that one element (a DOM write, not an inline `style` attribute, which is what makes it work under a policy with no `'unsafe-inline'`). +**A typeface and the corners.** Four system-font stacks — nothing is downloaded +from anywhere, which is deliberate and a GDPR matter: a stylesheet that pulls a +font from fonts.gstatic.com tells Google the IP address of everyone who reads +the site. A fifth option takes an uploaded `.woff2`, self-hosted, sniffed by its +`wOF2` signature and capped at 400 KB; it is named ahead of the old stack in the +`font-family`, so a font that fails to load leaves a readable site rather than a +browser default. The screen carries a fold-out warning about missing accented +glyphs, file size, synthesised bold — and about **licensing**, which is the part +with a real cost: a font is software, a desktop licence is not a webfont +licence, and that liability follows the platform to every organisation it is +installed for. SIL OFL and Apache-2.0 are the safe ones. + +Roundness is one setting driving all four `--radius-*` tokens, because a site +whose cards are round and whose buttons are square looks like two sites. + **No SVG and no ICO.** The logo takes PNG, JPG or WebP and the favicon PNG only, both identified from their bytes by the same sniffer the wall uses. An SVG is XML that can carry script and would be served from our own origin; ICO would be one @@ -1111,6 +1126,37 @@ needs nothing — it walks `content/` only, and `data/` and `static/` are outsid it. A site with no `data/brand.yaml` builds byte-for-byte the HTML it built before any of this existed, which is asserted by building both ways. +### 11.18b Identidad — what the site is called and where to find it + +*Gestión* → **Identidad**, superadministrator only. The name and the one-line +tagline **in the three languages**, the association's accounts elsewhere, a +public email, a city and street, a default share picture and the footer line. + +All of it used to be `config.yaml`, which meant it could only be changed by +somebody with the repository — the thing this phase exists to end. Same +architecture as Marca: SQLite first for the members area, then a commit of +`data/site.yaml`, so a git outage never blocks a change that does not need git. + +**Hugo cannot have `config.yaml` overridden by a data file.** The name and +tagline are therefore read through `partials/site-name.html` and +`site-tagline.html`, which prefer `site.Data.site` and fall back to the config — +and every template that shows either calls one of them, so the two cannot drift. +A site with no `data/site.yaml` builds byte-for-byte what it built before, which +is asserted by building both ways. + +**Only what was actually set is written.** A file repeating the config's own +values back at it would make the fallback meaningless and freeze today's +defaults for good, so the form shows them as placeholders rather than as values +— a prefilled form saves the fallback the first time anybody presses the button. + +The contact fields are not decoration: they become `ContactPoint` and +`PostalAddress` in the `Organization` schema, which is what puts an association +in a *local* search result rather than only a web one. The social links become +`sameAs`, which is how a search or answer engine knows an Instagram account and +this site are the same body. Both are checked on the way in — a link must be +`https://`, because these render in the footer of every public page and +`javascript:` in an `href` is a script running on vienalatina.com. + ### 11.19 The chrome on a phone **The public menu opens from a ☰ below 768px**, and above it is the horizontal @@ -1147,6 +1193,43 @@ In the members area the navigation **wraps** on a phone rather than scrolling: six sections over two lines shows all six, where a swipe strip would have left Calendario and Gestión off the right edge with nothing to say they were there. +### 11.20 The three admin tools + +**Estado del sistema** (superadministrator). WordPress's Site Health, and it +earns its place for a specific reason: every outage in this project has been a +configuration fact invisible until somebody hit it. It asks the running system +rather than a file — the content token is **exercised** against the repository +rather than checked for emptiness, which is the single most valuable line on the +page, because "present" was never the problem; the mail host is connected to; +the newest backup is named with its age and size; free disk is reported; and +every setting `.env.example` documents that the container does not have is +listed with what stops working without it. **It changes nothing**, deliberately: +a diagnostic screen that can also act is one somebody uses to act without +reading. + +**Registro de actividad** (superadministrator). Who changed a role, approved or +returned a proposal, touched the look or the identity, suspended or erased +somebody. Deliberately not a general event store — no page views, no successful +sign-ins; a log that records everything is a log nobody reads. `activity.log()` +never raises: an administrator who could not be appointed because the note about +it could not be saved is a worse outcome than a gap in the notes. On erasure the +actor is **cleared and not cascaded** — that a role was changed is the +association's record, whose name was on it is the erased person's data. + +**Biblioteca de medios** (administrators and above). Every picture the public +site carries, with the posts that use each. **Orphans are the point**: a picture +is committed when a post is written, and deleting the post leaves it in the +repository, deployed, referenced by nothing, for good — there has never been a +way to see one. They sort to the top and are the only rows with a delete button; +a picture in use is refused by the handler and not merely hidden, because a +broken image on a published page is worse than an orphan nobody sees. It reads +`content_cache.image`, which is what makes "does anything use this?" a query +rather than a re-read of every post's frontmatter on every page view. + +Open to administrators, unlike the other two, because they are the people who +upload — and the worst an administrator can do here is remove a picture from a +post they could already have edited. + ## 12. Make Gitea look like the site Members sign in to `/comunidad/` through Gitea, so Gitea's sign-in form and its diff --git a/themes/vienalatina/assets/css/main.css b/themes/vienalatina/assets/css/main.css index eabe987..6e8188a 100644 --- a/themes/vienalatina/assets/css/main.css +++ b/themes/vienalatina/assets/css/main.css @@ -4041,3 +4041,14 @@ a.notif-card__message:hover { .agenda__day--busy { display: block; } .agenda__number { display: inline-block; margin-right: 8px; } } + +/* The association's accounts elsewhere, in the footer. Set in + Gestión → Identidad; absent entirely on a site that has set none. */ +.site-foot__social { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 14px; + margin-bottom: 10px; + font-size: 0.85rem; +} diff --git a/themes/vienalatina/layouts/_default/baseof.html b/themes/vienalatina/layouts/_default/baseof.html index 0399b0c..87897a7 100644 --- a/themes/vienalatina/layouts/_default/baseof.html +++ b/themes/vienalatina/layouts/_default/baseof.html @@ -3,7 +3,7 @@ - {{ if not .IsHome }}{{ .Title }} — {{ end }}{{ .Site.Title }} + {{ if not .IsHome }}{{ .Title }} — {{ end }}{{ partial "site-name.html" . }} {{ partial "seo-head.html" . }} {{ $css := resources.Get "css/main.css" | minify | fingerprint }} diff --git a/themes/vienalatina/layouts/partials/brand-head.html b/themes/vienalatina/layouts/partials/brand-head.html index 38fad14..1d5405c 100644 --- a/themes/vienalatina/layouts/partials/brand-head.html +++ b/themes/vienalatina/layouts/partials/brand-head.html @@ -19,7 +19,17 @@ {{ $tokens := "" }} {{ range $name, $value := .tokens }}{{ $tokens = printf "%s--%s:%s;" $tokens $name $value }}{{ end }} {{ $sheet := "" }} -{{ with $tokens }}{{ $sheet = printf ":root{%s}" . }}{{ end }} +{{/* The uploaded typeface first, so the @font-face is declared before anything + asks for the family. `font-display: swap` deliberately: the alternative + shows nothing until the file arrives, and a blank article on a slow phone + is worse than one that changes typeface a moment after it appears. */}} +{{ with .font }} +{{ $sheet = printf "@font-face{font-family:\"VLPropia\";src:url(%s) format('woff2');font-weight:100 900;font-display:swap}" . }} +{{ end }} +{{ with $tokens }}{{ $sheet = printf "%s:root{%s}" $sheet . }}{{ end }} +{{/* On `body`, because that is where main.css sets the stack and a custom + property would need every rule to opt in. */}} +{{ with .font_stack }}{{ $sheet = printf "%sbody{font-family:%s}" $sheet . }}{{ end }} {{ with $.Site.Data.brand.custom_css }}{{ $sheet = printf "%s\n%s" $sheet . }}{{ end }} {{ with $sheet }} {{ $brand := resources.FromString "css/brand.css" . | minify | fingerprint }} diff --git a/themes/vienalatina/layouts/partials/footer.html b/themes/vienalatina/layouts/partials/footer.html index e736803..49dce01 100644 --- a/themes/vienalatina/layouts/partials/footer.html +++ b/themes/vienalatina/layouts/partials/footer.html @@ -8,5 +8,21 @@ {{ end }} {{ end }} -

    {{ .Site.Title }} © {{ now.Format "2006" }}

    + {{/* The association's accounts elsewhere. Read through a variable for the + same reason as the name — a field lookup on nil fails the build on a + site that has not set any. `rel="me"` is what lets Mastodon verify a + link back, and costs nothing on the others. */}} + {{ $social := dict }} + {{ with site.Data.site }}{{ with .social }}{{ $social = . }}{{ end }}{{ end }} + {{ with $social }} + + {{ end }} + + {{ $footer := "" }} + {{ with site.Data.site }}{{ $footer = .footer_text }}{{ end }} +

    {{ with $footer }}{{ . }}{{ else }}{{ partial "site-name.html" $ }} © {{ now.Format "2006" }}{{ end }}

    diff --git a/themes/vienalatina/layouts/partials/header.html b/themes/vienalatina/layouts/partials/header.html index d82c76a..76d4664 100644 --- a/themes/vienalatina/layouts/partials/header.html +++ b/themes/vienalatina/layouts/partials/header.html @@ -15,9 +15,10 @@ {{ $logo := "" }}{{ $stamp := "0" }} {{ with site.Data.brand }}{{ $logo = .logo }}{{ $stamp = .stamp }}{{ end }} {{ with $logo }} - + {{ else }} - {{ .Site.Title }} + {{ partial "site-name.html" . }} {{ end }} diff --git a/themes/vienalatina/layouts/partials/seo-head.html b/themes/vienalatina/layouts/partials/seo-head.html index 251ddff..bd4718f 100644 --- a/themes/vienalatina/layouts/partials/seo-head.html +++ b/themes/vienalatina/layouts/partials/seo-head.html @@ -4,7 +4,7 @@ {{ $localeMap := .Site.Params.localeMap }} {{ $locale := index $localeMap .Language.Lang | default "es_ES" }} {{ $desc := "" }} -{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = .Site.Params.description }}{{ end }} +{{ if .IsPage }}{{ $desc = .Description | default (.Summary | plainify | truncate 200) }}{{ else }}{{ $desc = partial "site-tagline.html" . }}{{ end }} {{/* One line, always. A summary pulled out of the body arrives with the line breaks the prose had, and a newline inside og:description is a card that renders raggedly in some readers and truncated in others. */}} @@ -20,9 +20,13 @@ Absolute, because WhatsApp, Signal, Mastodon and Bluesky all fetch it from outside and a relative path means nothing to them. */}} -{{ $brandLogo := "" }} +{{ $brandLogo := "" }}{{ $chosen := "" }} {{ with site.Data.brand }}{{ $brandLogo = .logo }}{{ end }} -{{ $fallback := or $brandLogo .Site.Params.defaultImage }} +{{ with site.Data.site }}{{ $chosen = .share_image }}{{ end }} +{{/* The picture chosen in Identidad wins over the logo, which wins over the + one in config.yaml: most sites want their logo and the field exists for the + ones that want something else. */}} +{{ $fallback := or $chosen (or $brandLogo .Site.Params.defaultImage) }} {{ $image := "" }} {{ with .Params.image }}{{ $image = . | absURL }} {{ else }}{{ with $fallback }}{{ $image = . | absURL }}{{ end }}{{ end }} @@ -42,7 +46,7 @@ {{ if and .IsPage (eq .Section "post") }} {{/* ---- Article ---- */}} - + @@ -124,8 +128,8 @@ {{ else if .IsHome }} {{/* ---- Home ---- */}} - - + + @@ -138,14 +142,33 @@ {{ end }} +{{/* The organisation, as a search or answer engine reads it. Everything + overridable lives in Gestión → Identidad; `areaServed` stays here because a + city is a fact about this association and not a setting. */}} {{ $org := dict "@context" "https://schema.org" "@type" "Organization" - "name" .Site.Title + "name" (partial "site-name.html" .) "url" .Site.Home.Permalink - "description" .Site.Params.description + "description" (partial "site-tagline.html" .) "areaServed" (dict "@type" "City" "name" "Wien" "addressCountry" "AT") }} +{{ with site.Data.site }} +{{/* sameAs is how an engine knows an Instagram account and this site are one + body — the single highest-value field here for being found at all. */}} +{{ with .sameAs }}{{ $org = merge $org (dict "sameAs" .) }}{{ end }} +{{ with .email }} +{{ $org = merge $org (dict "contactPoint" (dict + "@type" "ContactPoint" "contactType" "general" "email" .)) }} +{{ end }} +{{ if or .city .street }} +{{ $address := dict "@type" "PostalAddress" "addressCountry" "AT" }} +{{ with .city }}{{ $address = merge $address (dict "addressLocality" .) }}{{ end }} +{{ with .street }}{{ $address = merge $address (dict "streetAddress" .) }}{{ end }} +{{ with .phone }}{{ $org = merge $org (dict "telephone" .) }}{{ end }} +{{ $org = merge $org (dict "address" $address) }} +{{ end }} +{{ end }} {{/* The same fallback as the share card: the admin's logo, then the configured default. This is the field a search engine uses to put a mark beside the organisation's name, so it should be the logo somebody actually uploaded. */}} @@ -184,7 +207,7 @@ document about the organisation rather than an article, hence WebPage rather than BlogPosting, and no author: a page is the site speaking. */}} - + diff --git a/themes/vienalatina/layouts/partials/site-name.html b/themes/vienalatina/layouts/partials/site-name.html new file mode 100644 index 0000000..34c5115 --- /dev/null +++ b/themes/vienalatina/layouts/partials/site-name.html @@ -0,0 +1,20 @@ +{{- /* The site's name, from Gestión → Identidad when it has been set there and + from config.yaml when it has not. + + Hugo cannot have `config.yaml` overridden by a data file, so this partial + is the override: every template that shows the name calls it, and the two + sources cannot drift. A site with no data/site.yaml renders exactly what it + rendered before any of this existed. + + Read through a variable rather than as site.Data.site.languages..name, + because on a site with no data file that chain is a field lookup on nil and + fails the build — which is the state every install starts in. */ -}} +{{- $name := site.Title -}} +{{- with site.Data.site -}} +{{- with .languages -}} +{{- with index . $.Site.Language.Lang -}} +{{- with .name }}{{ $name = . }}{{ end -}} +{{- end -}} +{{- end -}} +{{- end -}} +{{- $name -}} diff --git a/themes/vienalatina/layouts/partials/site-tagline.html b/themes/vienalatina/layouts/partials/site-tagline.html new file mode 100644 index 0000000..3876f59 --- /dev/null +++ b/themes/vienalatina/layouts/partials/site-tagline.html @@ -0,0 +1,12 @@ +{{- /* The one-line description of the site, from Gestión → Identidad or from + config.yaml. See site-name.html for why it is a partial and why it reads + through a variable. */ -}} +{{- $tagline := site.Params.description -}} +{{- with site.Data.site -}} +{{- with .languages -}} +{{- with index . $.Site.Language.Lang -}} +{{- with .tagline }}{{ $tagline = . }}{{ end -}} +{{- end -}} +{{- end -}} +{{- end -}} +{{- $tagline -}}