An instance that can be somebody else's

A name, a tagline, a logo, a favicon and the launcher icons derived from it; the
Middle-earth strings as data; themes as token sets; and a stylesheet for what
none of that reaches. All four are on one page, in one settings group.

The snapshot is a Jinja global over a process-level cache, because render() has
no session and four render paths never reach it at all -- the sign-in page, the
error pages, the offline page and the SSE fragments. A context value would have
had to be threaded through every one and would still have missed those. It being
a global is also what lets mark() branch on an uploaded logo without any of its
six call sites learning about branding; the macro that renders the sidebar link
is called brandlink now, because a macro imported as `brand` shadows the global
for the whole template and took out every page at once.

Defaults in code and overrides in the database, as the prompt fragments do, with
one difference stated in the module: an empty fragment means off, an empty
flavour string means the shipped wording. And blanked rather than dropped --
settings_store.update merges, so an omitted key leaves what was stored last time
and "I typed the default back in" would store something different from "I changed
nothing".

A custom theme sets a handful of tokens and inherits the rest, and the
inheritance is a CSS fact: tokens.css matches [data-base="shire"] as well as
[data-theme="shire"], so a custom light theme lands on parchment rather than four
light colours on near-black. Values are validated on read rather than on save,
because a theme written straight into the settings table still has to produce a
stylesheet that parses -- a `}` in a value ends the rule and silently breaks
every rule after it. The soft variants are derived from the accent, or a changed
accent leaves focus rings in the old hue and reads as half-working.

/branding.css is a route, not an inline block: an external stylesheet has no HTML
context to escape from. The link carries a content hash, so a save is not left to
the browser's cache, and it is deliberately outside the service worker's precache
list, which is versioned by the release.

The instance name moved off /admin/general rather than being duplicated there.
An upgrade keeps it: the general row is read as a seed exactly while the branding
row has never mentioned the name, which is `key in row` and not `row[key] is
truthy` -- the two read alike would resurrect the old name underneath a cleared
one.

The theme list stops being a hard-coded pair in five places. Every failure mode
in that area is silent, so it is driven under a DOM stub as well as tested.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jaroslav Beneš
2026-08-06 15:42:25 +02:00
co-authored by Claude Opus 5
parent 46066150d9
commit 78e5717f77
67 changed files with 1887 additions and 117 deletions
+145
View File
@@ -98,6 +98,151 @@ def delete_model_image(filename: str) -> None:
path.unlink(missing_ok=True)
# --- Branding assets -----------------------------------------------------------
# The logo, the favicon and the launcher icons derived from them. A separate
# directory from the model avatars because the *route* differs: these are served
# unauthenticated, since the sign-in page and the web app manifest both need
# them and neither has a session to check.
#
# SVG stays excluded, and this is where somebody will most want it. Every entry
# in ALLOWED_TYPES is a format that cannot execute in an `<img>`; an SVG can, and
# these are the one set of files served to somebody who is not signed in.
# What a launcher asks for, and what `<link rel="apple-touch-icon">` wants.
# Generated from the uploaded logo rather than asked for separately: an
# administrator who has a logo has said everything they need to say, and five
# upload fields to fill in by hand is how three of them end up wrong.
ICON_SIZES: dict[str, int] = {
"icon-192": 192,
"icon-512": 512,
"apple-touch": 180,
"favicon": 32,
}
# The maskable icon has to survive being cropped to a circle, so the artwork
# sits inside the safe zone with the background showing around it. 80% is the
# standard's own guidance and is what the shipped icon already uses.
MASKABLE_SIZE = 512
MASKABLE_INSET = 0.8
def branding_dir() -> Path:
path = settings.uploads_dir / "branding"
path.mkdir(parents=True, exist_ok=True)
return path
def save_branding_image(payload: bytes, declared_type: str) -> str:
"""Validate and store a logo or favicon. Returns the stored filename."""
if not payload:
raise UploadError("The file was empty.")
if len(payload) > MAX_BYTES:
raise UploadError(f"Images must be under {MAX_BYTES // (1024 * 1024)} MB.")
actual = _detect(payload)
if actual is None:
raise UploadError(
"That does not look like a PNG, JPEG, WEBP or GIF image. "
"SVG is deliberately not accepted: these files are served to people "
"who are not signed in, and an SVG can carry a script."
)
if declared_type and declared_type.split(";")[0].strip() != actual:
log.info("upload declared %s but is actually %s", declared_type, actual)
filename = f"{secrets.token_hex(16)}{ALLOWED_TYPES[actual]}"
(branding_dir() / filename).write_bytes(payload)
return filename
def derive_icons(payload: bytes) -> dict[str, str]:
"""Launcher icons from an uploaded logo, at the sizes a browser asks for.
Best-effort: an instance whose logo cannot be resized keeps the shipped
icons, which is a worse launcher tile and not a broken install. Pillow is
already a dependency (`services/files.py` uses it for attachments), so this
adds nothing to install.
Every output is PNG regardless of what came in, because that is what a
manifest icon has to be, and RGBA so a logo with a transparent background
stays one.
"""
try:
import io
from PIL import Image
except Exception: # noqa: BLE001 - Pillow missing is not a failed save
log.info("Pillow unavailable; keeping the shipped launcher icons")
return {}
try:
with Image.open(io.BytesIO(payload)) as source:
source.load()
image = source.convert("RGBA")
except Exception: # noqa: BLE001 - a file we stored but cannot read
log.info("could not read the uploaded logo for icons", exc_info=True)
return {}
paths: dict[str, str] = {}
for name, size in ICON_SIZES.items():
paths[name] = _write_png(_fitted(image, size, size), f"{name}")
# Cropped to a circle on Android, so the artwork is inset and the corners
# are filled rather than transparent -- a transparent maskable icon is
# rendered as a black square by some launchers.
canvas = _new_canvas(MASKABLE_SIZE, image)
inner = _fitted(image, int(MASKABLE_SIZE * MASKABLE_INSET), int(MASKABLE_SIZE * MASKABLE_INSET))
offset = (MASKABLE_SIZE - inner.width) // 2, (MASKABLE_SIZE - inner.height) // 2
canvas.alpha_composite(inner, offset)
paths["maskable"] = _write_png(canvas, "maskable")
return paths
def _fitted(image, width: int, height: int):
from PIL import Image
return image.copy().resize((width, height), Image.LANCZOS)
def _new_canvas(size: int, source):
"""A square the colour of the logo's top-left pixel, or transparent.
Sampling one pixel rather than averaging: a logo on a flat background gets
that background, which is what the inset needs, and a logo on a transparent
one gets transparency, which the composite below then fills.
"""
from PIL import Image
corner = source.getpixel((0, 0))
fill = corner if isinstance(corner, tuple) and len(corner) == 4 else (0, 0, 0, 0)
return Image.new("RGBA", (size, size), fill)
def _write_png(image, label: str) -> str:
import io
buffer = io.BytesIO()
image.save(buffer, format="PNG", optimize=True)
filename = f"{label}-{secrets.token_hex(8)}.png"
(branding_dir() / filename).write_bytes(buffer.getvalue())
return filename
def branding_image_path(filename: str) -> Path | None:
"""Resolve a stored branding filename, refusing anything outside the dir."""
if not filename or "/" in filename or "\\" in filename or filename.startswith("."):
return None
path = (branding_dir() / filename).resolve()
try:
path.relative_to(branding_dir().resolve())
except ValueError:
return None
return path if path.is_file() else None
def delete_branding_image(filename: str) -> None:
path = branding_image_path(filename)
if path is not None:
path.unlink(missing_ok=True)
def media_type_for(filename: str) -> str:
suffix = Path(filename).suffix.lower()
for media_type, extension in ALLOWED_TYPES.items():