**A signed-in member sees the members area from anywhere.** A slim bar above the
public header, with the same five sections /comunidad/ has. Those pages are
files on disk and get cached, so it is drawn in the browser: memberbar.js asks
/comunidad/sesion.json who is reading, and that endpoint is the only thing that
decides — a visitor is told `{"signed_in": false}` and the answer is never
cached. Sign-in also sets vl_sesion=1, a cookie holding one digit that scripts
can read, and without it the script makes no request at all: a stranger reading
one article costs the app nothing. It is a hint, never a credential — the
session cookie stays HttpOnly and signed, and a forged hint earns a reply saying
you are not signed in. Comunidad is now in the public menu in all three
languages, signed in or not.
**The public menu is built from the pages.** It was three names per language in
config.yaml, so a page published through Contenido never appeared on the site at
all and the German and Portuguese menus had to be kept in step by hand. Pages
carry `parent` (another page's basename — the one translate.py already uses to
pair siblings, so it holds in all three languages) and `weight`, both chosen in
the editor, and header.html builds two levels from them. URLs do not change: a
subpage is still /page/<slug>/, only the menu nests, so nothing in the Caddyfile
or the pipeline learns about folders. The dropdown is the theme's own, ported
from WordPress — hover, focus-within, inline on a phone, no script. A parent that
has been deleted is kept and labelled rather than silently dropped on the next
save.
**Sharing and the rest of SEO/GEO.** The groundwork was already here — hreflang,
Open Graph, Twitter card, BlogPosting, llms.txt, robots.txt naming the AI
crawlers — so this closes the gaps. Static pages had *none* of it and shared as
bare links; they now carry WebPage schema and the full set of tags. Both branches
gain og:image with an alt and a twitter:image, falling back to params.defaultImage
(empty until there is a logo, which is the one line to fill in then). The home
page gains Organization with areaServed Wien and a sameAs list; posts and pages
gain BreadcrumbList, and an article's structured data now carries the author's
profile URL. An optional FAQ — `pregunta|respuesta` per line — renders at the
foot of the page and as FAQPage schema, because current guidance for generative
engines puts exactly that shape at the top of what gets quoted, and schema
describing something invisible is what search engines penalise. translate.py
carries both new fields: image_alt joins the translated keys, and faq is
translated half by half so the separator survives.
**The writing boxes.** A markdown toolbar and a Vista previa on every box where
somebody writes prose, opted in with data-markdown. The preview POSTs to
/comunidad/previsualizar and renders with render.to_html — the same function the
board and the site use, so it cannot promise something publishing will not
deliver; a markdown parser in the browser would be a second opinion about what
somebody's text means. Choosing a picture now shows a thumbnail with its name and
size before anything is uploaded, which is the only reason `blob:` joins img-src:
a handle to bytes already in the page, reaching no network.
All of it ours, no dependency added, under a policy that loads scripts from this
origin only. Verified by building the site with Hugo 0.135, the version the
pipeline runs: the nested menu, the page's share tags, the FAQ schema matching
the rendered section, and llms.txt listing the pages.
463 tests pass.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NizVpJ2dwzCbjCrTLCjeHn
177 lines
8.0 KiB
Python
177 lines
8.0 KiB
Python
"""Guards on the templates themselves.
|
|
|
|
These check one thing that no request-level test can: the Content-Security-
|
|
Policy makes a whole category of markup silently inert rather than broken, so
|
|
nothing at runtime will ever fail to tell you about it.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
TEMPLATES = sorted((Path(__file__).resolve().parents[1] / "templates").glob("*.html"))
|
|
INLINE_HANDLER = re.compile(r"\son[a-z]+\s*=", re.IGNORECASE)
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_no_inline_event_handlers(template):
|
|
"""`default-src 'self'` with no 'unsafe-inline' means the browser ignores
|
|
an onsubmit="" attribute without complaining. A delete button written that
|
|
way loses its confirmation dialog and nobody finds out until something is
|
|
deleted by accident. Use data-confirm, handled in static/board.js.
|
|
|
|
Comments stripped first, like the two guards below: base.html explains in a
|
|
Jinja comment why its account menu is a <details> rather than a button with
|
|
an onclick, and a guard that fails on its own reasoning gets deleted rather
|
|
than obeyed."""
|
|
found = INLINE_HANDLER.findall(
|
|
JINJA_COMMENT.sub("", template.read_text(encoding="utf-8")))
|
|
assert not found, f"{template.name} has inline handler(s): {found}"
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_no_inline_style_blocks(template):
|
|
"""The same policy, the same silence, a different symptom.
|
|
|
|
`default-src 'self'` covers style-src too, and 'self' does not permit an
|
|
inline <style>. The browser drops the whole block without a word, and the
|
|
page arrives in Times New Roman with blue links — which is exactly how the
|
|
public profile page shipped. Put it in static/ and link it, where the
|
|
policy allows it and the browser caches it.
|
|
"""
|
|
# Comments stripped first: profile.html explains in a Jinja comment why it
|
|
# has no <style> block, and a guard that trips on its own documentation is
|
|
# a guard people delete.
|
|
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
assert "<style" not in html, (
|
|
f"{template.name} has an inline <style> block, which the CSP ignores. "
|
|
"Move it to apps/board/static/ and link it with url_for('static', …)."
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_no_table_cell_is_told_to_be_a_flex_container(template):
|
|
"""`.actions` is display:flex, and a <td> given it stops being a table cell.
|
|
|
|
It leaves the row's layout, so its bottom border is drawn at its own content
|
|
height rather than the row's and the columns' rules no longer meet. Nothing
|
|
errors, nothing logs, the page just looks subtly broken — which is how it
|
|
survived two rounds of somebody looking straight at it. The flex row belongs
|
|
in a <div> inside the cell.
|
|
"""
|
|
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
offenders = re.findall(r"<td[^>]*class=[\"'][^\"']*\bactions\b[^\"']*[\"']", html)
|
|
assert not offenders, (
|
|
f"{template.name} puts a flex class on a <td>: {offenders}. "
|
|
"Wrap the buttons in <div class=\"actions\"> inside the cell instead."
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_every_post_form_carries_a_csrf_token(template):
|
|
"""The hook in app.py rejects a POST without one, so a form that forgets it
|
|
is a button that always fails — and fails with a 400 that reads like the
|
|
page is broken rather than like a missing field."""
|
|
html = template.read_text(encoding="utf-8")
|
|
forms = re.findall(r"<form[^>]*method=[\"']post[\"'][^>]*>(.*?)</form>", html,
|
|
re.IGNORECASE | re.DOTALL)
|
|
for form in forms:
|
|
assert "csrf_token" in form, f"{template.name} has a POST form without a CSRF token"
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_nothing_links_to_the_account_server_logout(template):
|
|
"""A link there is a GET, and that route is POST-only, so the browser gets
|
|
a 404 and the session it was meant to end carries on. We shipped exactly
|
|
that and it went unnoticed for a week, because a dead link on a page nobody
|
|
reaches twice looks like nothing at all.
|
|
|
|
It cannot be fixed by turning the link into a form either: the POST needs a
|
|
CSRF token belonging to that other domain, which is unreadable from here by
|
|
design. The page has to tell the member what to do instead."""
|
|
html = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
assert "/user/logout" not in html, (
|
|
f"{template.name} links to /user/logout, which answers 404 to a GET"
|
|
)
|
|
|
|
|
|
# --- the name of the software behind the login ---------------------------
|
|
#
|
|
# Members sign in through an OAuth provider that happens to be Gitea. They are
|
|
# never told so: as far as anyone using vienalatina.com is concerned there is
|
|
# one site, and a stray brand name in an error message is the seam showing.
|
|
# Comments and docstrings are exempt — the code has to stay honest about what
|
|
# it talks to, and neither reaches a browser.
|
|
|
|
JINJA_COMMENT = re.compile(r"\{#.*?#\}", re.DOTALL)
|
|
|
|
|
|
@pytest.mark.parametrize("template", TEMPLATES, ids=lambda p: p.name)
|
|
def test_no_template_shows_the_name_of_the_account_server(template):
|
|
body = JINJA_COMMENT.sub("", template.read_text(encoding="utf-8"))
|
|
assert "Gitea" not in body, (
|
|
f"{template.name} shows 'Gitea' to the member; call it el servidor de "
|
|
"cuentas, or put the remark in a {# Jinja comment #}"
|
|
)
|
|
|
|
|
|
def test_no_message_in_the_code_shows_it_either():
|
|
"""String literals only, docstrings excluded, and case-sensitive on
|
|
purpose: `gitea_login` and `gitea_tokens` are column names nobody sees, so
|
|
only the capitalised prose form is worth failing on."""
|
|
import ast
|
|
|
|
offenders = []
|
|
for path in sorted(Path(__file__).resolve().parents[1].glob("*.py")):
|
|
tree = ast.parse(path.read_text(encoding="utf-8"))
|
|
docstrings = {
|
|
doc for node in ast.walk(tree)
|
|
if isinstance(node, (ast.Module, ast.FunctionDef,
|
|
ast.AsyncFunctionDef, ast.ClassDef))
|
|
and (doc := ast.get_docstring(node, clean=False))
|
|
}
|
|
offenders += [
|
|
f"{path.name}:{node.lineno}: {node.value!r}"
|
|
for node in ast.walk(tree)
|
|
if isinstance(node, ast.Constant) and isinstance(node.value, str)
|
|
and "Gitea" in node.value and node.value not in docstrings
|
|
]
|
|
assert not offenders, "\n".join(offenders)
|
|
|
|
|
|
# --- the writing boxes opt in ---------------------------------------------
|
|
|
|
PROSE_BOXES = {
|
|
"thread_form.html": "body",
|
|
"comment_form.html": "body",
|
|
"thread.html": "body",
|
|
"conversation.html": "body",
|
|
"submission_form.html": "body",
|
|
"content_form.html": "body",
|
|
"profile_edit.html": "bio",
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("name,box", sorted(PROSE_BOXES.items()))
|
|
def test_every_prose_box_has_the_markdown_toolbar(name, box):
|
|
"""`data-markdown` is what board.js attaches the toolbar and the preview to.
|
|
A box that forgets it loses both silently — the page still works, it is just
|
|
the plain textarea it always was, which nobody files as a bug."""
|
|
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
|
|
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
|
|
assert opening, f"{name} has no textarea #{box}"
|
|
assert "data-markdown" in opening.group(0), (
|
|
f"{name}: #{box} is prose and should carry data-markdown")
|
|
|
|
|
|
def test_the_fields_that_are_not_prose_stay_plain():
|
|
"""The links and FAQ boxes are parsed line by line, not rendered. A bold
|
|
button there would put asterisks into a value, not into writing."""
|
|
for name, box in (("profile_edit.html", "links"), ("content_form.html", "faq")):
|
|
html = (Path(__file__).resolve().parents[1] / "templates" / name).read_text(encoding="utf-8")
|
|
opening = re.search(rf'<textarea id="{box}"[^>]*>', html)
|
|
assert opening and "data-markdown" not in opening.group(0), name
|