diff --git a/apps/board/app.py b/apps/board/app.py index 03138ad..8f9d53d 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -94,10 +94,11 @@ 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, content, events, home, members, messages, - profiles, submissions, uploads) + from . import (auth, board, brand, content, events, home, members, + messages, profiles, 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(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 +123,13 @@ def create_app(overrides: dict | None = None) -> Flask: def _year(): return {"current_year": datetime.now(timezone.utc).year} + @app.context_processor + def _brand(): + # Not lazy, unlike the badges below: base.html draws the stylesheet + # link, the logo and the favicon on every page, so there is no render + # that would save the query by deferring it. + return {"brand": brand.state()} + @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 new file mode 100644 index 0000000..8b84ea5 --- /dev/null +++ b/apps/board/brand.py @@ -0,0 +1,613 @@ +"""The look of both halves of the site, owned by the admin rather than by me. + +Until this existed, the brand colours were two identical `:root` blocks — one in +`themes/vienalatina/assets/css/main.css`, one in `apps/board/static/board.css` — +with a comment in the second saying *"If the brand colours change, change them +in both."* There was no logo anywhere and no favicon in either ``. Every +one of those is a change only somebody with the repository could make. + +**The dictionary below is now the single source of truth for the palette**, and +`apps/board/tests/test_brand.py` parses both stylesheets and fails if either +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. + +### The two destinations + +One form, saved to two places, because the two halves cannot read the same +store: + +* **SQLite**, for the members area, which must render correctly when the git + server is unreachable — the same rule the private calendar follows. +* **Git** (`data/brand.yaml` and `static/brand/…`), for the public site, which + is files on disk built by Hugo and has no database to read. + +SQLite is written first and the commits follow. If Gitea is down the change +still takes effect here, the row keeps `published_at` NULL, and the screen says +so with a button to try the publish again. The other order would let a git +outage block a change that does not need git. + +### Why the custom CSS is a file and not a `", + follow_redirects=True) + + assert "no puede contener" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_an_enormous_css_box_is_refused(client, db, post, admin): + response = save(post, custom_css="a{}" * 20_000, follow_redirects=True) + + assert "caracteres" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_the_screen_never_loads_the_custom_css(client, post, admin): + """The reason an admin can always undo a mistake: `* { display: none }` in + the box breaks every page except this one.""" + save(post, custom_css="* { display: none }") + + page = client.get("/comunidad/gestion/marca").get_data(as_text=True) + other = client.get("/comunidad/gestion").get_data(as_text=True) + + assert "marca.css" not in page + assert "marca.css" in other + assert "Restaurar lo de fábrica" in page + + +# --- the two pictures ----------------------------------------------------- + +def test_a_logo_is_sniffed_not_trusted(client, db, post, admin): + """The same check as every other upload: the extension comes from the + bytes. A GIF called logo.png is a GIF.""" + response = save(post, logo=(io.BytesIO(GIF), "logo.png"), + content_type="multipart/form-data", follow_redirects=True) + + assert "es un gif" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_a_png_logo_is_kept_and_served(app, client, db, post, admin): + save(post, logo=(io.BytesIO(PNG), "vienalatina.png"), + content_type="multipart/form-data") + + name = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"] + assert name and name.endswith(".png") + with app.app_context(): + from apps.board import uploads + assert uploads.directory().joinpath(name).exists() + + # Public on purpose: it is in the of the sign-in page. + client.get("/comunidad/logout") + assert client.get(f"/comunidad/marca/{name}").status_code == 200 + + +def test_a_picture_that_is_not_the_current_one_is_not_served(client, db, post, admin): + save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data") + first = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"] + + save(post, logo=(io.BytesIO(PNG), "dos.png"), content_type="multipart/form-data") + + assert client.get(f"/comunidad/marca/{first}").status_code == 404 + + +def test_a_replaced_logo_goes_off_disk(app, client, db, post, admin): + save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data") + first = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"] + + save(post, logo=(io.BytesIO(PNG), "dos.png"), content_type="multipart/form-data") + + with app.app_context(): + from apps.board import uploads + assert not uploads.directory().joinpath(first).exists() + + +def test_the_favicon_is_png_only(client, db, post, admin): + """ICO and SVG are both refused, for different reasons: the sniffer + identifies bytes by a prefix and an SVG is XML that can carry script.""" + response = save(post, favicon=(io.BytesIO(GIF), "icono.gif"), + content_type="multipart/form-data", follow_redirects=True) + + assert "hace falta png" in response.get_data(as_text=True) + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + + +def test_the_logo_and_the_favicon_reach_the_chrome(client, post, admin): + save(post, logo=(io.BytesIO(PNG), "logo.png"), + favicon=(io.BytesIO(PNG), "icono.png"), + content_type="multipart/form-data") + + body = client.get("/comunidad/").get_data(as_text=True) + + assert "site-bar__logo" in body + assert 'rel="icon"' in body + assert "site-bar__brand-text" not in body + + +# --- publishing to the public site ---------------------------------------- + +@pytest.fixture(autouse=True) +def unreachable(monkeypatch): + """No test in this file talks to a real git server. + + Autouse and not optional: every save tries to publish, so without this each + one would open a socket to git.vienalatina.com and wait for it to fail. The + tests that care about the commit ask for `repo` as well, whose patches are + applied after these and therefore win. + """ + def refuse(*args, **kwargs): + raise brand.gitea.GiteaError("No se pudo contactar con el servidor de git.") + for name in ("list_directory", "read_file", "write_file", "delete_file"): + monkeypatch.setattr(brand.gitea, name, refuse) + + +def test_the_commit_carries_the_colours_and_the_pictures(db, post, admin, repo): + save(post, **{"token-brand": "#1b5e20", "custom_css": ".x { color: red }"}, + logo=(io.BytesIO(PNG), "vienalatina.png"), + favicon=(io.BytesIO(PNG), "icono.png"), + content_type="multipart/form-data") + + assert set(repo.files) == {"data/brand.yaml", + "static/brand/logo.png", + "static/brand/favicon.png"} + yaml = repo.files["data/brand.yaml"].decode("utf-8") + assert ' brand: "#1b5e20"' in yaml + assert 'logo: "/brand/logo.png"' in yaml # the path Hugo serves it at + assert 'favicon: "/brand/favicon.png"' in yaml + assert "custom_css: |\n .x { color: red }" in yaml + # Only the differences, exactly as the stylesheet does it. + assert "surface:" not in yaml + assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"] + + +def test_a_logo_in_another_format_does_not_leave_the_old_one_behind(post, admin, repo): + """`static/brand/logo.png` and `logo.webp` would otherwise both sit in the + repository, deployed, with only one of them referenced.""" + save(post, logo=(io.BytesIO(PNG), "uno.png"), content_type="multipart/form-data") + assert "static/brand/logo.png" in repo.files + + webp = b"RIFF\x00\x00\x00\x00WEBP" + b"\x00" * 64 + save(post, logo=(io.BytesIO(webp), "dos.webp"), content_type="multipart/form-data") + + assert "static/brand/logo.webp" in repo.files + assert "static/brand/logo.png" not in repo.files + + +def test_a_save_survives_the_git_server_being_down(client, db, post, admin): + """The order this is written in. SQLite first, so a change that does not + need git is not blocked by git — and the screen says the public site is a + step behind rather than pretending it is not.""" + response = save(post, **{"token-brand": "#1b5e20"}, follow_redirects=True) + + row = db.execute("SELECT tokens_json, published_at FROM brand").fetchone() + assert json.loads(row["tokens_json"]) == {"brand": "#1b5e20"} + assert row["published_at"] is None + assert "Pendiente de publicar" in response.get_data(as_text=True) + assert "--brand: #1b5e20;" in client.get("/comunidad/marca.css").get_data(as_text=True) + + +def test_the_retry_publishes_what_was_already_saved(db, post, admin, monkeypatch, repo): + """What the *Reintentar publicar* button is for: the colours are in SQLite + and the commit never happened.""" + def refuse(*args, **kwargs): + raise brand.gitea.GiteaError("caído") + + # Only the write, and put it back by hand rather than with + # `monkeypatch.undo()` — which would also undo the `repo` fixture's own + # patches and leave the retry talking to the real git server. + working = brand.gitea.write_file + monkeypatch.setattr(brand.gitea, "write_file", refuse) + save(post, **{"token-brand": "#1b5e20"}) + assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"] is None + + monkeypatch.setattr(brand.gitea, "write_file", working) + post("/comunidad/gestion/marca/publicar") + + assert ' brand: "#1b5e20"' in repo.files["data/brand.yaml"].decode("utf-8") + assert db.execute("SELECT published_at FROM brand").fetchone()["published_at"] + + +# --- restoring ------------------------------------------------------------ + +def test_restoring_empties_the_row_and_the_disk(app, client, db, post, admin): + save(post, **{"token-brand": "#1b5e20"}, ) + save(post, logo=(io.BytesIO(PNG), "logo.png"), content_type="multipart/form-data") + name = db.execute("SELECT logo_name FROM brand").fetchone()["logo_name"] + + post("/comunidad/gestion/marca/restaurar") + + assert db.execute("SELECT COUNT(*) AS n FROM brand").fetchone()["n"] == 0 + with app.app_context(): + from apps.board import uploads + assert not uploads.directory().joinpath(name).exists() + css = client.get("/comunidad/marca.css").get_data(as_text=True) + assert ":root" not in css # nothing to override any more + assert "site-bar__brand-text" in client.get("/comunidad/").get_data(as_text=True) + + +# --- erasure -------------------------------------------------------------- + +def test_erasing_the_admin_leaves_the_brand_standing(client, db, post, owner_id, + make_member, sign_in): + """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"}) + + sign_in(owner_id) + post(f"/comunidad/miembros/{admin_id}/eliminar") + + 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 diff --git a/apps/board/tests/test_content.py b/apps/board/tests/test_content.py index 083a628..bd112c7 100644 --- a/apps/board/tests/test_content.py +++ b/apps/board/tests/test_content.py @@ -9,7 +9,6 @@ import the real translate.py and run its parser over what the editor wrote. from __future__ import annotations -import hashlib import importlib.util import io import sys @@ -18,6 +17,7 @@ from pathlib import Path import pytest from apps.board import content, gitea +from apps.board.tests.conftest import FakeRepo # noqa: F401 (used by the `repo` fixture) REPO_ROOT = Path(__file__).resolve().parents[3] @@ -35,54 +35,6 @@ def _load_translate(): translate = _load_translate() -class FakeRepo: - """A repository in a dict, with shas that change when content does.""" - - def __init__(self): - self.files: dict[str, bytes] = {} - self.commits: list[str] = [] - self.authors: list[dict] = [] - self.reads = 0 - - @staticmethod - def _sha(data: bytes) -> str: - return hashlib.sha1(data).hexdigest() - - def list_directory(self, path, token=None): - out = [] - for name, data in self.files.items(): - if name.startswith(path + "/") and "/" not in name[len(path) + 1:]: - out.append({"name": name.rsplit("/", 1)[1], "path": name, - "type": "file", "sha": self._sha(data)}) - return out - - def read_file(self, path, token=None): - self.reads += 1 - if path not in self.files: - raise gitea.GiteaError("Ese archivo ya no existe.") - return self.files[path].decode("utf-8"), self._sha(self.files[path]) - - def write_file(self, path, data, message, token=None, sha=None, member=None): - if sha and self.files.get(path) is not None and self._sha(self.files[path]) != sha: - raise gitea.StaleFile("Alguien más guardó este archivo mientras lo editabas.") - self.files[path] = data - self.commits.append(message) - self.authors.append(gitea._identity(member)) - return self._sha(data) - - def delete_file(self, path, sha, message, token=None, member=None): - self.files.pop(path, None) - self.commits.append(message) - - -@pytest.fixture -def repo(monkeypatch): - fake = FakeRepo() - for name in ("list_directory", "read_file", "write_file", "delete_file"): - monkeypatch.setattr(gitea, name, getattr(fake, name)) - return fake - - @pytest.fixture def editor(db, make_member, sign_in): """An admin. The editor commits through the server's own content token diff --git a/config.yaml b/config.yaml index 2052eb3..b683dd2 100644 --- a/config.yaml +++ b/config.yaml @@ -79,10 +79,13 @@ languages: params: # The picture a share card falls back on when a post or page has none, and the - # organisation's logo in the structured data. One path — /uploads/algo.png — - # and WhatsApp, Signal, Mastodon and Bluesky all start showing an image. Left - # empty until there is a logo to put here; a link then shares as title and - # description, which is what happens today. + # organisation's logo in the structured data. + # + # **The logo uploaded in Gestión → Marca is used first**, so this is now only + # for a site that wants a different share picture from its logo — a photo of + # the city, say. One path (/uploads/algo.png) and WhatsApp, Signal, Mastodon + # and Bluesky all start showing an image. Empty, with no logo either, means a + # link shares as title and description. defaultImage: "" # The organisation's profiles elsewhere, for `sameAs` in the Organization diff --git a/docs/server-setup.md b/docs/server-setup.md index e155e8d..cb6abbd 100644 --- a/docs/server-setup.md +++ b/docs/server-setup.md @@ -1008,6 +1008,72 @@ 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 + +*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 +and a free CSS box. + +**`apps/board/brand.py`'s `FACTORY` is the single source of truth for the +palette.** The two `:root` blocks — `themes/vienalatina/assets/css/main.css` and +`apps/board/static/board.css` — each still carry their own copy, because they are +served by different things and each has to stand alone; what changed is that +`apps/board/tests/test_brand.py` parses both and fails the build if either +disagrees with `FACTORY`. The comment that used to say *"If the brand colours +change, change them in both"* was an instruction, which is the weakest kind of +guarantee there is. + +**One save, two destinations**, because the two halves cannot read the same +store: + +| Where | What | Why | +|---|---|---| +| SQLite, table `brand`, one row | the tokens, the custom CSS, both pictures under `/data/uploads` | the members area must render when the git server is down | +| the content repository: `data/brand.yaml`, `static/brand/logo.*`, `static/brand/favicon.png` | the same values | the public site is files on disk and has no database | + +**SQLite first, then the commits.** If Gitea is unreachable the change still +takes effect in the members area, `published_at` stays NULL, and the screen says +so with a *Reintentar publicar* button. The other order would let a git outage +block a change that does not need git. A colour therefore reaches +vienalatina.com on the next pipeline run — a couple of minutes — and the members +area immediately. + +Three details worth knowing before changing any of it: + +* **Only what differs from the factory is stored**, as JSON in one column. A + token added here later arrives with its default already in place for every + existing install, which a snapshot of all thirteen would not. +* **`--brand-dark`, `--brand-soft` and `--brand-softer` are worked out from + `--brand`** in HLS (hue and saturation kept, lightness moved), so an admin + picks one colour and gets a coherent set. Each can be overridden in + *Avanzado*. With no brand colour stored, the factory hexes are used verbatim — + deriving from an unchanged colour would shift the palette by a rounding error + the first time anybody opened the screen. +* **A WCAG contrast warning, not a refusal.** Text on background below 4.5:1, + or white on the brand colour below 3:1, is named with its ratio and saved + anyway. An admin may have a reason; what this prevents is shipping an + unreadable site without once being told. + +**The Marca screen deliberately does not load the generated stylesheet.** Every +other page does. That is what keeps *Restaurar lo de fábrica* reachable after +somebody puts `* { display: none }` in the CSS box — and the reason the colours +an admin picks do not show on the page where they pick them. The live preview +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'`). + +**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 +more branch in the sniffer for a format every current browser no longer needs. + +The pictures are committed to stable paths, so saving a new logo replaces the +file instead of leaving every previous one deployed and unreferenced; a logo +saved in a different format has its predecessor deleted. `scripts/translate.py` +needs nothing — it walks `content/` only, and `data/` and `static/` are outside +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. + ## 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/layouts/_default/baseof.html b/themes/vienalatina/layouts/_default/baseof.html index e7fd25e..0399b0c 100644 --- a/themes/vienalatina/layouts/_default/baseof.html +++ b/themes/vienalatina/layouts/_default/baseof.html @@ -7,6 +7,7 @@ {{ partial "seo-head.html" . }} {{ $css := resources.Get "css/main.css" | minify | fingerprint }} + {{ partial "brand-head.html" . }} {{ range .AlternativeOutputFormats -}} diff --git a/themes/vienalatina/layouts/partials/brand-head.html b/themes/vienalatina/layouts/partials/brand-head.html new file mode 100644 index 0000000..38fad14 --- /dev/null +++ b/themes/vienalatina/layouts/partials/brand-head.html @@ -0,0 +1,31 @@ +{{/* The admin's colours and the favicon, from data/brand.yaml. + + That file is written by the members area — Gestión → Marca commits it + through the contents API, the pipeline runs, and the colours arrive here on + the next build. The whole partial is inside a `with`, so a site with no + brand.yaml emits nothing at all and its HTML is byte-identical to before + this existed. + + Built with resources.FromString rather than written into a