diff --git a/apps/board/app.py b/apps/board/app.py index 15224f5..07c719a 100644 --- a/apps/board/app.py +++ b/apps/board/app.py @@ -148,8 +148,13 @@ def create_app(overrides: dict | None = None) -> Flask: # pointing at another site will not load — which for a private board is # the right answer anyway, since an external image is a request that # tells someone else who read the thread and when. + # + # `blob:` is in img-src for one thing only: the thumbnail of a picture + # somebody has just chosen and not yet uploaded. A blob URL is a handle + # to bytes already in this page; it reaches no network and cannot be + # pointed at another site. response.headers["Content-Security-Policy"] = ( - "default-src 'self'; img-src 'self' data:; frame-ancestors 'none'" + "default-src 'self'; img-src 'self' data: blob:; frame-ancestors 'none'" ) return response diff --git a/apps/board/auth.py b/apps/board/auth.py index 7f9c489..d5bf348 100644 --- a/apps/board/auth.py +++ b/apps/board/auth.py @@ -121,7 +121,40 @@ def login(): passwords.prune_attempts() get_db().execute("UPDATE members SET last_seen_at = datetime('now') WHERE id = ?", (member["id"],)) - return redirect(safe_next(target)) + return remember_session(redirect(safe_next(target))) + + +# --- the hint the public site reads -------------------------------------- +# +# The static pages on vienalatina.com are files on disk; nothing there knows who +# is looking. The members' bar is therefore drawn by a script that asks this app +# — and asking on every page view, for every stranger who ever lands on the +# site, to be told they are nobody, is a request per page for nothing. +# +# So sign-in also sets this: a second cookie holding the digit 1, readable by +# that script, saying only "somebody signed in on this browser once". Without it +# the script makes no request at all. It is a hint and never a credential: the +# real session cookie stays HttpOnly and signed, and `sesion.json` decides +# everything. Somebody who sets this by hand gets a bar that says they are not +# signed in. +SESSION_HINT = "vl_sesion" + + +def remember_session(response): + response.set_cookie( + SESSION_HINT, "1", + max_age=60 * 60 * 24 * 30, + secure=current_app.config["SESSION_COOKIE_SECURE"], + httponly=False, # the whole point: a script has to read it + samesite="Lax", + path="/", # including the static site, which is why it exists + ) + return response + + +def forget_session(response): + response.delete_cookie(SESSION_HINT, path="/") + return response def invite_url(token: str) -> str: @@ -207,4 +240,4 @@ def logout(): """ session.clear() flash("Has cerrado sesión.", "ok") - return redirect(url_for("auth.login")) + return forget_session(redirect(url_for("auth.login"))) diff --git a/apps/board/content.py b/apps/board/content.py index 3835c8c..3680b54 100644 --- a/apps/board/content.py +++ b/apps/board/content.py @@ -76,6 +76,10 @@ SAFE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*\.es\.md$") # link somewhere else. AUTHOR_URL = re.compile(r"^/[A-Za-z0-9][A-Za-z0-9._-]{0,38}$") +# A page's basename, as it appears in acerca.es.md — which is what another page +# names when it hangs under it. +PAGE_BASENAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}$") + # --- the contract with translate.py -------------------------------------- @@ -114,6 +118,17 @@ def frontmatter_for(collection: str, form: dict) -> dict: fields["date"] = form["date"] fields["lang"] = "es" fields["manual_translation"] = form["manual_translation"] + if collection == "page": + # Only written when set, so a page that sits at the top of the menu has + # no `parent: ""` line for somebody to wonder about later. + if form.get("parent"): + fields["parent"] = form["parent"] + if form.get("weight"): + fields["weight"] = form["weight"] + if form.get("faq"): + fields["faq"] = form["faq"] + if form.get("image_alt"): + fields["image_alt"] = form["image_alt"] if collection == "post": if form["categories"]: fields["categories"] = form["categories"] @@ -237,6 +252,26 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: # editing it, so saving a correction must not re-sign the post. Checked on # the way back in because a hidden field is only a convention — the URL has # to be a path on this site and nothing else. + # A page's place in the menu. `parent` is another page's basename — the one + # translate.py uses to pair siblings, so a parent chosen once holds in all + # three languages — and the menu is built from these, not from a list in + # config.yaml that nobody remembers to edit. + parent = request.form.get("parent", "").strip() + if parent and not PAGE_BASENAME.match(parent): + parent = "" + try: + weight = max(0, min(999, int(request.form.get("weight", "") or 50))) + except ValueError: + weight = 50 + + # Questions and answers, one `pregunta|respuesta` per line — the same shape + # the profile links field uses, and parsed the same way: a line without a + # separator is dropped rather than published half-formed. They are rendered + # on the page and as FAQPage structured data, which is the shape an answer + # engine quotes most readily. + faq = clean_faq(request.form.get("faq", "")) + image_alt = request.form.get("image_alt", "").strip()[:200] + author = request.form.get("author", "").strip()[:80] author_url = request.form.get("author_url", "").strip() if author_url and not AUTHOR_URL.match(author_url): @@ -257,6 +292,8 @@ def _read_form(collection: str) -> tuple[dict, str, list[str]]: "image": image, "manual_translation": request.form.get("manual_translation") == "on", "author": author, "author_url": author_url, + "parent": parent, "weight": weight, + "faq": faq, "image_alt": image_alt, } return fields, body, errors @@ -295,6 +332,27 @@ def commit_picture(data: bytes, filename: str, author=None) -> str: return f"/uploads/{name}" +def clean_faq(raw: str) -> list[str]: + """`pregunta|respuesta` per line, kept only when both halves are there. + + Stored as the lines themselves rather than as a list of dicts: the template + and the schema both split on the first separator, and a YAML list of strings + survives translate.py's `dict(fm)` copy unchanged, which a nested structure + would too but less legibly in a diff. + """ + entries = [] + for line in raw.splitlines(): + question, separator, answer = line.strip().partition("|") + if not separator: + continue + question, answer = question.strip(), answer.strip() + if question and answer: + entries.append(f"{question[:200]}|{answer[:600]}") + if len(entries) >= 10: + break + return entries + + def _upload_image() -> str: upload = request.files.get("picture") if not upload or not upload.filename: @@ -378,7 +436,8 @@ def new(collection: str): if request.method == "GET": return render_template("content_form.html", collection=collection, meta=meta, categories=CATEGORIES, item=None, fields=None, - body="", today=date_type.today().isoformat()) + body="", today=date_type.today().isoformat(), + parents=possible_parents(collection)) fields, body, errors = _read_form(collection) if errors: @@ -429,11 +488,16 @@ def edit(collection: str, name: str): # people's words, applied to the byline. "author": fm.get("author", ""), "author_url": fm.get("author_url", ""), + "parent": fm.get("parent", ""), + "weight": fm.get("weight", ""), + "faq": "\n".join(fm.get("faq") or []), + "image_alt": fm.get("image_alt", ""), } return render_template("content_form.html", collection=collection, meta=meta, categories=CATEGORIES, item={"name": name, "sha": sha}, fields=fields, body=body, - today=date_type.today().isoformat()) + today=date_type.today().isoformat(), + parents=possible_parents(collection, name)) fields, body, errors = _read_form(collection) sha = request.form.get("sha", "") @@ -493,12 +557,33 @@ def preview(collection: str): return render_template("content_form.html", collection=collection, meta=meta, categories=CATEGORIES, item=item, fields=fields, body=body, today=date_type.today().isoformat(), + parents=possible_parents(collection, + item["name"] if item else ""), preview_html=to_html(body)) +def possible_parents(collection: str, exclude: str = "") -> list[dict]: + """The pages a page may hang under, for the select in the form. + + Only pages have a parent, and a page cannot be its own. A failure to reach + the git server returns an empty list rather than an error: not being able to + offer the choice is no reason to refuse to open the form. + """ + if collection != "page": + return [] + try: + items = listing("page") + except gitea.GiteaError: + return [] + return [{"base": item["name"].removesuffix(".es.md"), "title": item["title"]} + for item in items if item["name"] != exclude] + + def _back_to_form(collection, meta, fields, body, errors, item): for message in errors: flash(message, "error") return render_template("content_form.html", collection=collection, meta=meta, categories=CATEGORIES, item=item, fields=fields, body=body, - today=date_type.today().isoformat()), 400 + today=date_type.today().isoformat(), + parents=possible_parents(collection, + item["name"] if item else "")), 400 diff --git a/apps/board/home.py b/apps/board/home.py index 29446e3..40f149f 100644 --- a/apps/board/home.py +++ b/apps/board/home.py @@ -13,17 +13,22 @@ page is the only way to reach anything. from __future__ import annotations -from flask import Blueprint, g, render_template +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 -from .security import admin_required, login_required +from .render import excerpt, to_html +from .security import admin_required, csrf_token, login_required bp = Blueprint("home", __name__) RECENT = 5 +# The longest text the preview will render. The forms themselves cap what can be +# saved; this is only here so a crafted request cannot ask for a megabyte of +# markdown to be parsed on every keystroke. +BODY_MAX = 100_000 + @bp.route("/") @login_required @@ -92,6 +97,73 @@ def index(): state_labels=submissions.STATE_LABELS) +@bp.route("/sesion.json") +def session_state(): + """Who is signed in, for the bar the public site draws. + + vienalatina.com is files on disk; it cannot know who is reading it, and + baking the answer into those files would mean caching one member's name for + the next visitor. So the browser asks here instead, and this is the only + place that decides — including which sections to offer, read from the same + rule the navigation uses, so the two cannot drift. + + Three properties worth stating, because each is a way this leaks: + + * **A visitor gets `{"signed_in": false}` and nothing else.** No names, no + counts, no hint about who else exists. + * **`no-store`.** A cached answer is somebody else's name on a shared + machine, or a bar that stays after signing out. + * **No badge counts.** They would need queries on every public page view, + for a number nobody can act on until they are inside anyway. + """ + if g.member is None: + return _no_store(jsonify({"signed_in": False})) + + sections = [ + {"label": "Inicio", "url": url_for("home.index")}, + {"label": "Muro", "url": url_for("board.threads")}, + {"label": "Privados", "url": url_for("messages.inbox")}, + {"label": "Publicaciones", "url": url_for("submissions.index")}, + ] + if g.member["role"] in ("owner", "admin"): + sections.append({"label": "Gestión", "url": url_for("home.gestion")}) + + return _no_store(jsonify({ + "signed_in": True, + "name": g.member["display_name"] or g.member["gitea_login"], + "sections": sections, + "profile": url_for("profiles.edit"), + "logout": url_for("auth.logout"), + # Signing out is a POST, so the bar needs the token to render a real + # form. Handing it to a script on our own pages gives nothing away: a + # page on another origin cannot read this response — no CORS header + # allows it — and the session cookie is SameSite=Lax, so it is not sent + # with a cross-site POST in the first place. + "csrf": csrf_token(), + })) + + +def _no_store(response): + response.headers["Cache-Control"] = "no-store" + return response + + +@bp.route("/previsualizar", methods=["POST"]) +@login_required +def preview(): + """Render markdown the way the site will, for the Vista previa button. + + A round trip rather than a markdown parser in the browser, deliberately. The + preview has to agree with what gets published, and the only way to guarantee + that is to render it with the same function — `render.to_html`, with raw HTML + disabled, which is the whole of the XSS defence here. A second parser in + JavaScript would be a second opinion about what somebody's text means, and + the two would disagree the first time anybody wrote something unusual. + """ + body = request.form.get("body", "")[:BODY_MAX] + return _no_store(jsonify({"html": to_html(body)})) + + @bp.route("/gestion") @admin_required def gestion(): diff --git a/apps/board/static/board.css b/apps/board/static/board.css index c2f6123..e5b25f1 100644 --- a/apps/board/static/board.css +++ b/apps/board/static/board.css @@ -540,3 +540,60 @@ input[type="file"] { } .person-card__actions form { margin: 0; } .person-card__actions p { margin: 0; } + +/* --- the writing boxes ------------------------------------------------- */ + +.md-bar { + display: flex; + flex-wrap: wrap; + gap: 0.25rem; + margin-bottom: 0.35rem; +} +.md-bar__button { + min-width: 2rem; + padding: 0.25rem 0.5rem; + border: 1px solid var(--border-light); + border-radius: var(--radius-sm); + background: var(--surface); + color: var(--muted); + font-size: 0.85rem; + cursor: pointer; + line-height: 1.4; +} +.md-bar__button:hover { border-color: var(--brand); color: var(--brand-dark); } +.md-bar__button--wide { margin-left: auto; } + +.md-preview { + margin: 0.5rem 0 1rem; + padding: 0.85rem 1rem; + border: 1px dashed var(--border); + border-radius: var(--radius-md); + background: var(--surface-soft); + line-height: 1.6; +} +.md-preview :first-child { margin-top: 0; } +.md-preview :last-child { margin-bottom: 0; } +.md-preview img { max-width: 100%; border-radius: var(--radius-sm); } + +/* What you just chose, before it is uploaded. */ +.file-strip { + display: flex; + flex-wrap: wrap; + gap: 0.6rem; + margin: 0.5rem 0 0; +} +.file-strip__item { margin: 0; width: 120px; } +.file-strip__item img { + display: block; + width: 120px; + height: 90px; + object-fit: cover; + border-radius: var(--radius-sm); + border: 1px solid var(--border-light); +} +.file-strip__item figcaption { + margin-top: 0.2rem; + font-size: 0.72rem; + color: var(--subtle); + overflow-wrap: anywhere; +} diff --git a/apps/board/static/board.js b/apps/board/static/board.js index 07a6290..a69b6ad 100644 --- a/apps/board/static/board.js +++ b/apps/board/static/board.js @@ -13,3 +13,152 @@ document.addEventListener("submit", function (event) { event.preventDefault(); } }); + +// --- the writing boxes ---------------------------------------------------- +// +// A toolbar, a preview and thumbnails, all of it ours. Not because a library +// would be wrong, but because the Content-Security-Policy here loads scripts +// from this origin only, and vendoring an editor means owning its updates +// forever — for buttons that wrap a selection in asterisks. +// +// Everything below attaches on load and leaves anything it does not recognise +// alone, so a form that has not opted in behaves exactly as it did. + +(function () { + "use strict"; + + // What each button does to the selected text. `wrap` goes on both sides, + // `prefix` goes at the start of every selected line. + var TOOLS = [ + { label: "N", title: "Negrita", wrap: "**" }, + { label: "I", title: "Cursiva", wrap: "_" }, + { label: "H", title: "Título", prefix: "## " }, + { label: "“”", title: "Cita", prefix: "> " }, + { label: "•", title: "Lista", prefix: "- " }, + { label: "🔗", title: "Enlace", link: true } + ]; + + function apply(box, tool) { + var start = box.selectionStart; + var end = box.selectionEnd; + var selected = box.value.slice(start, end); + var replacement; + + if (tool.link) { + var url = window.prompt("Dirección del enlace", "https://"); + if (!url) return; + replacement = "[" + (selected || "texto") + "](" + url + ")"; + } else if (tool.prefix) { + // Line by line, so marking three lines as a list marks three lines. + replacement = (selected || "").split("\n").map(function (line) { + return line.indexOf(tool.prefix) === 0 ? line : tool.prefix + line; + }).join("\n"); + } else { + replacement = tool.wrap + (selected || "texto") + tool.wrap; + } + + box.setRangeText(replacement, start, end, "end"); + box.focus(); + // Fires the input event frameworks and our own counters would expect; the + // browser does not fire one for a programmatic change. + box.dispatchEvent(new Event("input", { bubbles: true })); + } + + function toolbarFor(box) { + var bar = document.createElement("div"); + bar.className = "md-bar"; + TOOLS.forEach(function (tool) { + var button = document.createElement("button"); + button.type = "button"; // never a submit inside a form + button.className = "md-bar__button"; + button.title = tool.title; + button.textContent = tool.label; + button.addEventListener("click", function () { apply(box, tool); }); + bar.appendChild(button); + }); + + var preview = document.createElement("button"); + preview.type = "button"; + preview.className = "md-bar__button md-bar__button--wide"; + preview.textContent = "Vista previa"; + var panel = document.createElement("div"); + panel.className = "md-preview"; + panel.hidden = true; + + preview.addEventListener("click", function () { + if (!panel.hidden) { + panel.hidden = true; + return; + } + var token = box.form && box.form.querySelector("input[name=csrf_token]"); + var data = new FormData(); + data.append("body", box.value); + data.append("csrf_token", token ? token.value : ""); + panel.textContent = "Un momento…"; + panel.hidden = false; + fetch("/comunidad/previsualizar", { + method: "POST", body: data, credentials: "same-origin" + }).then(function (response) { + return response.ok ? response.json() : null; + }).then(function (result) { + // The server rendered this with the same markdown the site uses, with + // raw HTML disabled, so what comes back is already safe to insert — + // and inserting it as text would show the tags instead of the writing. + panel.innerHTML = result ? result.html : ""; + if (!result) panel.textContent = "No se pudo generar la vista previa."; + }).catch(function () { + panel.textContent = "No se pudo generar la vista previa."; + }); + }); + + bar.appendChild(preview); + box.parentNode.insertBefore(bar, box); + box.parentNode.insertBefore(panel, box.nextSibling); + } + + // --- thumbnails of what was just chosen --------------------------------- + // + // So that attaching the wrong photograph is noticed before posting rather + // than after. createObjectURL gives a handle to bytes already in this page — + // nothing is uploaded until the form is submitted — which is what `blob:` in + // the image policy is there for. + function previewFiles(input) { + var strip = input.nextElementSibling; + if (!strip || !strip.classList.contains("file-strip")) { + strip = document.createElement("div"); + strip.className = "file-strip"; + input.parentNode.insertBefore(strip, input.nextSibling); + } + Array.prototype.forEach.call(strip.querySelectorAll("img"), function (img) { + URL.revokeObjectURL(img.src); // or every re-pick leaks one + }); + strip.textContent = ""; + + Array.prototype.forEach.call(input.files, function (file) { + if (file.type.indexOf("image/") !== 0) return; + var figure = document.createElement("figure"); + figure.className = "file-strip__item"; + var img = document.createElement("img"); + img.src = URL.createObjectURL(file); + img.alt = ""; + var caption = document.createElement("figcaption"); + caption.textContent = file.name + " · " + Math.round(file.size / 1024) + " KB"; + figure.appendChild(img); + figure.appendChild(caption); + strip.appendChild(figure); + }); + } + + document.addEventListener("DOMContentLoaded", function () { + Array.prototype.forEach.call( + document.querySelectorAll("textarea[data-markdown]"), toolbarFor); + + document.addEventListener("change", function (event) { + var input = event.target; + if (input.tagName === "INPUT" && input.type === "file" && + (input.accept || "").indexOf("image") !== -1) { + previewFiles(input); + } + }); + }); +})(); diff --git a/apps/board/templates/comment_form.html b/apps/board/templates/comment_form.html index f40c9a7..3aebf46 100644 --- a/apps/board/templates/comment_form.html +++ b/apps/board/templates/comment_form.html @@ -7,7 +7,7 @@
Menor número, más a la izquierda. 50 si da igual.
+ {% endif %} + {% if collection == 'post' %} - diff --git a/apps/board/templates/thread.html b/apps/board/templates/thread.html index cca3578..0a18f17 100644 --- a/apps/board/templates/thread.html +++ b/apps/board/templates/thread.html @@ -81,7 +81,7 @@ action="{{ url_for('board.comment', thread_id=thread.id) }}"> - diff --git a/apps/board/templates/thread_form.html b/apps/board/templates/thread_form.html index 0f4ee8e..b67f749 100644 --- a/apps/board/templates/thread_form.html +++ b/apps/board/templates/thread_form.html @@ -12,7 +12,7 @@ value="{{ thread.title if thread else '' }}"> - {# Only when writing, not when editing: the edit route does not read files, diff --git a/apps/board/tests/test_board.py b/apps/board/tests/test_board.py index 02b47bd..9083695 100644 --- a/apps/board/tests/test_board.py +++ b/apps/board/tests/test_board.py @@ -108,3 +108,40 @@ def test_the_cooldown_stops_a_double_submit(app, client, post, make_member, sign post("/comunidad/nuevo", {"title": "Segundo", "body": "Dos"}) count = db.execute("SELECT COUNT(*) AS n FROM threads").fetchone()["n"] assert count == 1 + + +# --- the preview behind the Vista previa button --------------------------- +# +# A round trip rather than a markdown parser in the browser: the preview has to +# agree with what gets published, and the only way to guarantee that is to +# render it with the same function the board and the site use. + +def test_the_preview_renders_the_same_markdown_the_board_does(post, make_member, sign_in): + sign_in(make_member("maria")) + + response = post("/comunidad/previsualizar", {"body": "**hola** y _adiós_"}) + + assert response.status_code == 200 + assert response.get_json()["html"] == "hola y adiós
\n" + + +def test_the_preview_drops_html_exactly_as_the_board_does(post, make_member, sign_in): + """`html=False` in render.py is the whole XSS defence. A preview that + rendered raw HTML would be a hole in the members area and a lie about what + posting is going to do.""" + sign_in(make_member("maria")) + + html = post("/comunidad/previsualizar", + {"body": ""}).get_json()["html"] + + assert " diff --git a/themes/vienalatina/layouts/_default/single.html b/themes/vienalatina/layouts/_default/single.html index e4ea2d3..896f008 100644 --- a/themes/vienalatina/layouts/_default/single.html +++ b/themes/vienalatina/layouts/_default/single.html @@ -48,6 +48,25 @@ {{ .Content }}