From 9d2f8c514f51f3099587425765d62a98e62e9906 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 19:34:21 +0000 Subject: [PATCH 1/3] Fix five high-severity findings from the security audit 1. Registration is closed unless ALLOW_REGISTRATION=True (register form, POST /auth/register and first-time Google/GitHub sign-in). Passwords need 8+ characters; missing fields, duplicate emails and non-JSON bodies get a 400 instead of a 500, and the register form no longer crashes on errors. 2. Todo routes check ownership: update_todo, delete_todo, mark_done, mark_status and exec_rules act only for the owner or an admin. The username or id in the request is no longer trusted. 3. Admin actions that change filtering are POST-only (rules_toggle enable/disable, stop/enable traffic, delete_block, auto_push, auto_import), so an in a blog post or a link can't fire them. State-changing requests whose Origin/Referer names another host are refused. 4. Note media is rendered inline only for image (not SVG), audio and video types; everything else is sent as a download, with nosniff. An uploaded HTML file can no longer run script with the viewer's login. 5. /auth/callback returns text/plain, so its code parameter can't inject script. All responses now carry X-Content-Type-Options: nosniff. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012k19dCKBK4J2UdDMJd5gLv --- README.md | 6 + config/settings.py | 5 + src/safe_family/app.py | 34 +- src/safe_family/auto_git/auto_git.py | 4 +- src/safe_family/core/auth.py | 50 ++- src/safe_family/templates/base.html | 2 +- .../templates/rules/suspicious_view.html | 16 +- src/safe_family/todo/todo.py | 40 +- src/safe_family/urls/blocker.py | 8 +- src/safe_family/urls/notes.py | 16 +- src/safe_family/urls/suspicious.py | 2 +- tests/conftest.py | 2 + tests/test_auth.py | 2 +- tests/test_auth_routes.py | 6 +- tests/test_auto_git.py | 2 +- tests/test_security_fixes.py | 401 ++++++++++++++++++ tests/test_suspicious.py | 2 +- tests/test_todo.py | 21 +- tests/test_todo_routes.py | 17 +- 19 files changed, 586 insertions(+), 50 deletions(-) create mode 100644 tests/test_security_fixes.py diff --git a/README.md b/README.md index fb33c18..5afbd74 100644 --- a/README.md +++ b/README.md @@ -343,6 +343,12 @@ Example `DB_PARAMS`: {"dbname":"safefamily","user":"safefamily","password":"secret","host":"localhost","port":5432} ``` +Accounts: +- `ALLOW_REGISTRATION`: new accounts are refused unless this is `True`. That + covers the register form, `POST /auth/register`, and first-time Google/GitHub + sign-in. Existing accounts can always log in. Set it to `True` only while + adding a family member, then remove it and restart the app. + Notesync: - `NOTESYNC_API_KEY` - `NOTESYNC_AUTH_CODE_TTL_SECONDS` diff --git a/config/settings.py b/config/settings.py index e0ef624..dc5e5ad 100644 --- a/config/settings.py +++ b/config/settings.py @@ -114,6 +114,11 @@ class Settings: "APP_MOTTO", ) + # New accounts (form, API and first-time Google/GitHub sign-in) are refused + # unless this is "True". Existing accounts can always log in. Turn it on + # only while adding a family member, then off again. + ALLOW_REGISTRATION = os.environ.get("ALLOW_REGISTRATION", "False") == "True" + # Countdown page settings (date in YYYY-MM-DD) COUNTDOWN_DATE = os.environ.get("COUNTDOWN_DATE", "") COUNTDOWN_DESCRIPTION = os.environ.get("COUNTDOWN_DESCRIPTION", "") diff --git a/src/safe_family/app.py b/src/safe_family/app.py index cab279d..86a3483 100644 --- a/src/safe_family/app.py +++ b/src/safe_family/app.py @@ -1,8 +1,9 @@ """Flask application factory for Safe Family project.""" from datetime import timedelta +from urllib.parse import urlsplit -from flask import Flask, jsonify, session +from flask import Flask, Response, jsonify, request, session from sqlalchemy.exc import SQLAlchemyError from config.logging import setup_logging @@ -25,6 +26,32 @@ from src.safe_family.users.users import user_bp MIN_SECRET_LENGTH = 32 +SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) + + +def reject_cross_site_writes() -> tuple[Response, int] | None: + """Refuse state-changing requests that a browser sent from another site. + + Browsers put the page's origin in the Origin header (or Referer) of every + cross-site POST. If it names a different host than ours, the request was + not made from our own pages (CSRF). Clients that send neither header + (the mobile app, scripts) are not browsers being tricked and pass through. + """ + if request.method in SAFE_METHODS: + return None + source = request.headers.get("Origin") or request.headers.get("Referer") + if not source: + return None + host = urlsplit(source).netloc + if host and host != request.host: + return jsonify({"error": "cross-site request blocked"}), 403 + return None + + +def add_security_headers(response: Response) -> Response: + """Stop browsers from guessing a different content type than we declared.""" + response.headers.setdefault("X-Content-Type-Options", "nosniff") + return response def _require_strong_secret(name: str, value: str | None) -> None: @@ -89,10 +116,13 @@ def create_app(): jwt.init_app(app) mail.init_app(app) + app.before_request(reject_cross_site_writes) + app.after_request(add_security_headers) + @app.context_processor def inject_motto() -> dict: """Inject the app motto into all templates.""" - return {"motto": settings.APP_MOTTO} + return {"motto": settings.APP_MOTTO, "registration_open": settings.ALLOW_REGISTRATION} app.context_processor(inject_nav_user) diff --git a/src/safe_family/auto_git/auto_git.py b/src/safe_family/auto_git/auto_git.py index 41926d5..e478c58 100644 --- a/src/safe_family/auto_git/auto_git.py +++ b/src/safe_family/auto_git/auto_git.py @@ -81,7 +81,7 @@ def rule_auto_commit(): logger.exception("Error adding files to git: %d", e.returncode) -@auto_git_bp.route("/auto_push") +@auto_git_bp.post("/auto_push") @admin_required def auto_push(): """Automatically commit and push block list changes to GitHub.""" @@ -90,7 +90,7 @@ def auto_push(): return redirect("/") -@auto_git_bp.route("/auto_import") +@auto_git_bp.post("/auto_import") @admin_required def auto_import(): """Automatically import block list from files into the database.""" diff --git a/src/safe_family/core/auth.py b/src/safe_family/core/auth.py index 4ad9cbb..fcbb138 100644 --- a/src/safe_family/core/auth.py +++ b/src/safe_family/core/auth.py @@ -44,6 +44,8 @@ logger = logging.getLogger(__name__) auth_bp = Blueprint("auth", __name__) OAUTH_STATE_TTL_SECONDS = 600 +MIN_PASSWORD_LENGTH = 8 +REGISTRATION_CLOSED = "Registration is closed. Ask the admin to add you." def require_api_key(view_func: Callable) -> Callable: @@ -114,17 +116,30 @@ def build_notesync_callback_url(code: str, client: str = "ios") -> str: @auth_bp.post("/register") def register_user(): """Register a new user.""" - data = getattr(g, "_json_data", None) or request.get_json() - user = User.get_user_by_username(username=data.get("username")) + if not settings.ALLOW_REGISTRATION: + return jsonify({"message": REGISTRATION_CLOSED}), 403 + data = getattr(g, "_json_data", None) or request.get_json(silent=True) or {} + username = (data.get("username") or "").strip() + email = (data.get("email") or "").strip() + password = data.get("password") or "" + if not username or not email: + return jsonify({"message": "Username and email are required"}), 400 + if len(password) < MIN_PASSWORD_LENGTH: + return jsonify( + {"message": f"Password must be at least {MIN_PASSWORD_LENGTH} characters"}, + ), 400 + user = User.get_user_by_username(username=username) if user is not None: return jsonify({"message": "Username already exists"}), 400 + if User.query.filter_by(email=email).first() is not None: + return jsonify({"message": "Email already in use"}), 400 new_user = User( - username=data.get("username"), - email=data.get("email"), + username=username, + email=email, role="user", # never trust a client-supplied role ) - new_user.set_password(data.get("password")) + new_user.set_password(password) new_user.save() return jsonify({"message": "User registered successfully"}), HTTP_CREATED @@ -214,6 +229,9 @@ def logout(): @auth_bp.route("/session-register", methods=["GET", "POST"]) def session_register(): """Register a new user via HTML form.""" + if not settings.ALLOW_REGISTRATION: + flash(REGISTRATION_CLOSED, "warning") + return redirect("/auth/login-ui") if request.method == "POST": username = request.form["username"] email = request.form["email"] @@ -221,7 +239,7 @@ def session_register(): confirmed_password = request.form["confirm_password"] if password != confirmed_password: flash("Passwords do not match", "danger") - return render_template("register.html") + return render_template("auth/register.html") json_data = { "username": username, @@ -235,10 +253,10 @@ def session_register(): # remove the temp data del g._json_data # noqa: SLF001 - our own attr on flask.g # noqa: SLF001 - our own attr on flask.g - _data, status_code = response + data, status_code = response if status_code != HTTP_CREATED: - flash("Invalid username or password", "danger") - return render_template("register.html") + flash(data.get_json().get("message", "Registration failed"), "danger") + return render_template("auth/register.html") flash("Registration successful! Please log in.", "success") return redirect("/auth/login-ui") return render_template("/auth/register.html") @@ -647,6 +665,10 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl if not user: user = User.query.filter_by(email=email).first() + if not user and not settings.ALLOW_REGISTRATION: + flash(REGISTRATION_CLOSED, "warning") + return redirect("/auth/login-ui") + if not user: new_user = User( id=github_id, @@ -704,6 +726,10 @@ def google_callback(): if not user: user = User.query.filter_by(email=email).first() + if not user and not settings.ALLOW_REGISTRATION: + flash(REGISTRATION_CLOSED, "warning") + return redirect("/auth/login-ui") + if not user: new_user = User( id=google_id, @@ -730,12 +756,16 @@ def google_callback(): def notesync_callback(): """Fallback page for notesync universal link callback.""" code = request.args.get("code", "") + plain = {"Content-Type": "text/plain; charset=utf-8"} if not code: - return "Missing auth code. Return to the app and try again.", 400 + return "Missing auth code. Return to the app and try again.", 400, plain + # The code comes straight from the URL: send it as plain text so a crafted + # link can never run script in the page (reflected XSS). return ( ( "Auth code received. You can return to the app to finish login. " f"If needed, copy this code: {code}" ), 200, + plain, ) diff --git a/src/safe_family/templates/base.html b/src/safe_family/templates/base.html index ded8c90..7ac1ab0 100644 --- a/src/safe_family/templates/base.html +++ b/src/safe_family/templates/base.html @@ -614,7 +614,7 @@ class="{% if request.endpoint in ('index.calc_guide', 'index.recipes', 'index.recipe_detail') %}active{% endif %}">Sheet {% else %} Login - Register + {% if registration_open %}Register{% endif %} {% endif %}
diff --git a/src/safe_family/templates/rules/suspicious_view.html b/src/safe_family/templates/rules/suspicious_view.html index 6ac5ef3..10d4a8b 100644 --- a/src/safe_family/templates/rules/suspicious_view.html +++ b/src/safe_family/templates/rules/suspicious_view.html @@ -108,8 +108,8 @@ {% endfor %} - + @@ -141,23 +141,23 @@
Rules Toggle
-
+
-
-
+
-
+ @@ -178,12 +178,12 @@ Analyze Logs
-
+
-
+ diff --git a/src/safe_family/todo/todo.py b/src/safe_family/todo/todo.py index 73490ad..b7c377d 100644 --- a/src/safe_family/todo/todo.py +++ b/src/safe_family/todo/todo.py @@ -5,7 +5,16 @@ import time as time_module from datetime import UTC, date, datetime, time, timedelta -from flask import Blueprint, flash, jsonify, redirect, render_template, request, url_for +from flask import ( + Blueprint, + abort, + flash, + jsonify, + redirect, + render_template, + request, + url_for, +) from psycopg2 import extensions as pg from src.safe_family.cli import weekly_metrics @@ -455,10 +464,21 @@ def todo_page(): # noqa: C901, PLR0915 - refactor backlog: split save/view path ) +def can_act_for(user: User | None, username: str | None) -> bool: + """Return True when ``user`` may change ``username``'s todo data. + + Only the owner or an admin may: the username/id in a URL or JSON body is + attacker-controlled and must never be trusted on its own. + """ + return user is not None and (user.role == "admin" or user.username == username) + + @todo_bp.route("/update_todo/", methods=["POST"]) @login_required def update_todo(selected_username: str): """Update tasks for the selected user.""" + if not can_act_for(get_current_username(), selected_username): + abort(403) todo_ids = request.form.getlist("todo_id") conn = get_db_connection() @@ -498,6 +518,8 @@ def update_todo(selected_username: str): @login_required def delete_todo(selected_username: str, todo_id: int): """Delete a specific to-do item for the selected user.""" + if not can_act_for(get_current_username(), selected_username): + abort(403) flash(f"Deleting todo: {todo_id} for user: {selected_username}", "info") conn = get_db_connection() cur = conn.cursor() @@ -528,7 +550,7 @@ def done_todo(): conn = get_db_connection() cur = conn.cursor() cur.execute( - "SELECT time_slot, task, COALESCE(completion_status, '') FROM todo_list WHERE id = %s", + "SELECT time_slot, task, COALESCE(completion_status, ''), username FROM todo_list WHERE id = %s", (todo_id,), ) row = cur.fetchone() @@ -536,7 +558,10 @@ def done_todo(): conn.close() return jsonify({"success": False, "error": "not found"}), 404 - time_slot, task, existing_status = row + time_slot, task, existing_status, task_owner = row + if not can_act_for(get_current_username(), task_owner): + conn.close() + return jsonify({"success": False, "error": "forbidden"}), 403 try: _, end_str = [t.strip() for t in time_slot.split("-")] end_time = datetime.strptime(end_str, "%H:%M").time() @@ -718,6 +743,10 @@ def mark_todo_status(): # noqa: PLR0911 - one early return per validation step return jsonify({"success": False, "error": "not found"}), 404 existing_status, time_slot, task_owner, task_name, log_date = row + if not can_act_for(user, task_owner): + conn.close() + logger.warning("mark_status: forbidden id=%s user=%s", todo_id, user) + return jsonify({"success": False, "error": "forbidden"}), 403 is_admin = user is not None and user.role == "admin" if existing_status and not is_admin: conn.close() @@ -872,6 +901,11 @@ def exec_rules(selected_user_id: str): # noqa: C901, PLR0911, PLR0912, PLR0915 flash("Please log in to access this feature.", "warning") return redirect("/auth/login-ui") + # A user may only run the rule assigned to themselves; the id in the URL + # is attacker-controlled. + if user.role != "admin" and str(user.id) != selected_user_id: + abort(403) + if not RULE_EXEC_LOCK.acquire(blocking=False): flash("Rules update already in progress.", "warning") return redirect(url_for("todo.todo_page")) diff --git a/src/safe_family/urls/blocker.py b/src/safe_family/urls/blocker.py index adfcd47..2caf69d 100644 --- a/src/safe_family/urls/blocker.py +++ b/src/safe_family/urls/blocker.py @@ -398,7 +398,7 @@ def rule_status_gateway(): return response -@rules_toggle_bp.route("/rules_toggle/enable_all") +@rules_toggle_bp.post("/rules_toggle/enable_all") @admin_required def rules_toggle_enable(): """Enable all blocking rules except AI.""" @@ -411,7 +411,7 @@ def rules_toggle_enable(): return redirect("/") -@rules_toggle_bp.route("/rules_toggle/disable_all") +@rules_toggle_bp.post("/rules_toggle/disable_all") @admin_required def rules_toggle_disable(): """Disable all blocking rules.""" @@ -449,7 +449,7 @@ def rules_disable_ai(): return redirect("/") -@rules_toggle_bp.route("/rules_toggle/stop_all_traffic") +@rules_toggle_bp.post("/rules_toggle/stop_all_traffic") @admin_required def stop_all_traffic(): """Stop all traffic by disabling the gateway on the router.""" @@ -458,7 +458,7 @@ def stop_all_traffic(): return redirect("/") -@rules_toggle_bp.route("/rules_toggle/enable_all_traffic") +@rules_toggle_bp.post("/rules_toggle/enable_all_traffic") @admin_required def enable_all_traffic(): """Allow all traffic by enabling the gateway on the router.""" diff --git a/src/safe_family/urls/notes.py b/src/safe_family/urls/notes.py index 2920b27..dd1301f 100644 --- a/src/safe_family/urls/notes.py +++ b/src/safe_family/urls/notes.py @@ -23,6 +23,9 @@ notes_bp = Blueprint("notes", __name__) +INLINE_MEDIA_PREFIXES = ("image/", "audio/", "video/") +SCRIPTABLE_MEDIA_TYPES = {"image/svg+xml"} + def _attach_local_timestamp(note: Note) -> None: updated_at = note.updated_at @@ -177,12 +180,19 @@ def notes_media(media_id: str): if not is_public: abort(404) - mimetype = media.content_type + mimetype = (media.content_type or "").split(";")[0].strip().lower() if media.filename.lower().endswith(".m4a"): mimetype = "audio/mp4" - return send_file( + # The content type was chosen by the uploader. Anything a browser could + # run as a page (HTML, SVG, XML, ...) is sent as a download instead of + # being rendered on this site's origin with the viewer's login. + inline = mimetype.startswith(INLINE_MEDIA_PREFIXES) and mimetype not in SCRIPTABLE_MEDIA_TYPES + response = send_file( io.BytesIO(media.data), - mimetype=mimetype, + mimetype=mimetype if inline else "application/octet-stream", download_name=media.filename, + as_attachment=not inline, ) + response.headers["X-Content-Type-Options"] = "nosniff" + return response diff --git a/src/safe_family/urls/suspicious.py b/src/safe_family/urls/suspicious.py index a46fd1c..38e6019 100644 --- a/src/safe_family/urls/suspicious.py +++ b/src/safe_family/urls/suspicious.py @@ -305,7 +305,7 @@ def add_block(): return redirect(f"/suspicious?date={date}") -@suspicious_bp.route("/delete_block/") +@suspicious_bp.post("/delete_block/") @admin_required def delete_block(block_id: int): """Delete a block rule based on user input. diff --git a/tests/conftest.py b/tests/conftest.py index 8830efd..704fff1 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -53,6 +53,8 @@ def _patch_test_secrets(monkeypatch): monkeypatch.setattr("config.settings.settings.APP_SECRET_KEY", TEST_SECRET) monkeypatch.setattr("config.settings.settings.JWT_SECRET_KEY", TEST_SECRET) monkeypatch.setattr("config.settings.settings.ADMIN_IDENTITY", "admin") + # Registration is closed by default; most tests exercise it while open. + monkeypatch.setattr("config.settings.settings.ALLOW_REGISTRATION", True) @pytest.fixture diff --git a/tests/test_auth.py b/tests/test_auth.py index 7e6ad3e..cbfa5d5 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -33,7 +33,7 @@ def test_admin_required_blocks_non_admin(client, monkeypatch): ) _set_session_token(client) - resp = client.get("/rules_toggle/enable_all") + resp = client.post("/rules_toggle/enable_all") assert resp.status_code == 302 assert "/auth/login-ui" in resp.location diff --git a/tests/test_auth_routes.py b/tests/test_auth_routes.py index 389bb59..690572a 100644 --- a/tests/test_auth_routes.py +++ b/tests/test_auth_routes.py @@ -28,7 +28,7 @@ def _save(self): "username": "alice", "email": "a@a.com", "role": "user", - "password": "secret", + "password": "secret-pw", }, ) assert resp.status_code == 201 @@ -43,7 +43,7 @@ def test_register_user_duplicate(client, monkeypatch): "username": "alice", "email": "a@a.com", "role": "user", - "password": "secret", + "password": "secret-pw", }, ) assert resp.status_code == 400 @@ -259,7 +259,7 @@ def test_register_user_ignores_client_role(client, monkeypatch): resp = client.post( "/auth/register", - json={"username": "probe", "email": "p@p.com", "role": "admin", "password": "secret"}, + json={"username": "probe", "email": "p@p.com", "role": "admin", "password": "secret-pw"}, ) assert resp.status_code == 201 diff --git a/tests/test_auto_git.py b/tests/test_auto_git.py index 6c332f5..af81d80 100644 --- a/tests/test_auto_git.py +++ b/tests/test_auto_git.py @@ -138,7 +138,7 @@ def close(self): with client.session_transaction() as sess: sess["access_token"] = "token" - resp = client.get("/auto_import") + resp = client.post("/auto_import") assert resp.status_code == 302 diff --git a/tests/test_security_fixes.py b/tests/test_security_fixes.py new file mode 100644 index 0000000..2da899a --- /dev/null +++ b/tests/test_security_fixes.py @@ -0,0 +1,401 @@ +"""Regression tests for the November 2026 security audit fixes. + +1. Registration is closed unless ALLOW_REGISTRATION is on; passwords need 8+ chars. +2. Todo routes act only for the owner or an admin. +3. State-changing admin routes are POST-only; cross-site writes are refused. +4. Note media that a browser could run as a page is sent as a download. +5. /auth/callback never reflects its code parameter as HTML. +""" + +import io +from datetime import datetime +from types import SimpleNamespace + +import pytest +from flask_jwt_extended import create_access_token + +from src.safe_family.core import auth +from src.safe_family.core.extensions import db +from src.safe_family.core.models import Media, Note, Tag, User +from src.safe_family.todo import todo +from src.safe_family.urls import blocker + +SETTINGS = "config.settings.settings" + + +def _make_user(user_id, username): + user = User(id=user_id, username=username, email=f"{username}@example.com", role="user") + user.set_password("long-enough-password") + db.session.add(user) + db.session.commit() + return user + + +def _login(app, client, user_id): + with app.app_context(): + token = create_access_token(identity=user_id) + with client.session_transaction() as sess: + sess["access_token"] = token + + +# ---- 1. registration ------------------------------------------------------ + + +def test_registration_is_closed_by_default(notesync_app, notesync_client, monkeypatch): + monkeypatch.setattr(f"{SETTINGS}.ALLOW_REGISTRATION", False) + body = {"username": "stranger", "email": "s@evil.test", "password": "long-enough-password"} + + assert notesync_client.post("/auth/register", json=body).status_code == 403 + assert User.query.count() == 0 + + page = notesync_client.get("/auth/session-register", follow_redirects=True).get_data(as_text=True) + assert "Registration is closed" in page + topbar = page.split('
', 1)[1].split("
", 1)[0] + assert "Register" not in topbar + + form = {"username": "s", "email": "s@evil.test", "password": "x" * 12, "confirm_password": "x" * 12} + assert notesync_client.post("/auth/session-register", data=form).status_code == 302 + assert User.query.count() == 0 + + +@pytest.mark.parametrize( + ("body", "message"), + [ + ({"username": "a", "email": "a@a.test", "password": "1"}, "at least 8"), + ({"username": "a", "email": "a@a.test"}, "at least 8"), + ({"username": "", "email": "a@a.test", "password": "long-enough"}, "required"), + ({"username": "a", "password": "long-enough"}, "required"), + ({"username": "other", "email": "alice@example.com", "password": "long-enough"}, "Email already in use"), + ], +) +def test_open_registration_validates_input(notesync_client, body, message): + _make_user("u1", "alice") + response = notesync_client.post("/auth/register", json=body) + assert response.status_code == 400 + assert message in response.get_json()["message"] + assert User.query.count() == 1 + + +def test_register_rejects_non_json_body_without_crashing(notesync_client): + response = notesync_client.post("/auth/register", data="not json", content_type="text/plain") + assert response.status_code == 400 + + +def test_register_form_shows_errors_instead_of_crashing(notesync_client): + form = {"username": "bob", "email": "b@b.test", "password": "long-enough", "confirm_password": "different"} + response = notesync_client.post("/auth/session-register", data=form) + assert response.status_code == 200 + assert "Passwords do not match" in response.get_data(as_text=True) + + form["confirm_password"] = form["password"] = "short" + response = notesync_client.post("/auth/session-register", data=form) + assert response.status_code == 200 + assert "at least 8 characters" in response.get_data(as_text=True) + assert User.query.count() == 0 + + +class _FakeResp: + def __init__(self, payload): + self.status_code = 200 + self._payload = payload + + def json(self): + return self._payload + + +def test_first_time_github_login_refused_when_registration_closed(notesync_client, monkeypatch): + monkeypatch.setattr(f"{SETTINGS}.ALLOW_REGISTRATION", False) + monkeypatch.setattr(auth, "_oauth_provider_available", lambda name: True) + monkeypatch.setattr(auth, "_read_oauth_state", lambda state: {"client": "web"}) + monkeypatch.setattr(auth.requests, "post", lambda *a, **k: _FakeResp({"access_token": "t"})) + user_info = {"id": 4242, "email": "new@person.test", "name": "New", "login": "new"} + monkeypatch.setattr( + auth.requests, + "get", + lambda url, **k: _FakeResp([] if url.endswith("/emails") else user_info), + ) + + response = notesync_client.get("/auth/github/callback?state=s&code=c") + + assert response.headers["Location"].endswith("/auth/login-ui") + assert User.query.count() == 0 + with notesync_client.session_transaction() as sess: + assert "access_token" not in sess + + +def test_existing_github_user_can_still_log_in_when_registration_closed(notesync_client, monkeypatch): + _make_user("4242", "known") + monkeypatch.setattr(f"{SETTINGS}.ALLOW_REGISTRATION", False) + monkeypatch.setattr(auth, "_oauth_provider_available", lambda name: True) + monkeypatch.setattr(auth, "_read_oauth_state", lambda state: {"client": "web"}) + monkeypatch.setattr(auth.requests, "post", lambda *a, **k: _FakeResp({"access_token": "t"})) + user_info = {"id": 4242, "email": "known@example.com", "name": "Known", "login": "known"} + monkeypatch.setattr( + auth.requests, + "get", + lambda url, **k: _FakeResp([] if url.endswith("/emails") else user_info), + ) + + notesync_client.get("/auth/github/callback?state=s&code=c") + + with notesync_client.session_transaction() as sess: + assert sess["access_token"] + + +# ---- 2. todo ownership ---------------------------------------------------- + + +class _Cursor: + def __init__(self, row=None): + self.row = row + self.queries = [] + + def execute(self, sql, params=None): + self.queries.append((" ".join(sql.split()), params)) + + def fetchone(self): + return self.row + + def fetchall(self): + return [] + + def close(self): + return None + + +class _Conn: + def __init__(self, row=None): + self.cursor_obj = _Cursor(row) + + def cursor(self): + return self.cursor_obj + + def commit(self): + return None + + def close(self): + return None + + +@pytest.fixture +def mallory(notesync_app, notesync_client, monkeypatch): + """A logged-in normal user, with the raw todo DB stubbed out.""" + _make_user("m1", "mallory") + _login(notesync_app, notesync_client, "m1") + monkeypatch.setattr(todo, "send_email_notification", lambda *a, **k: None) + monkeypatch.setattr(todo, "send_discord_notification", lambda *a, **k: None) + return notesync_client + + +def _writes(conn): + return [q for q, _ in conn.cursor_obj.queries if q.startswith(("UPDATE", "DELETE", "INSERT"))] + + +def test_can_act_for(): + alice = SimpleNamespace(username="alice", role="user") + admin = SimpleNamespace(username="boss", role="admin") + assert todo.can_act_for(alice, "alice") + assert todo.can_act_for(admin, "alice") + assert not todo.can_act_for(alice, "bob") + assert not todo.can_act_for(None, "alice") + + +def test_user_cannot_edit_or_delete_another_users_todo(mallory, monkeypatch): + conn = _Conn() + monkeypatch.setattr(todo, "get_db_connection", lambda: conn) + + assert mallory.post("/update_todo/alice", data={"todo_id": "7", "task_7": "hacked"}).status_code == 403 + assert mallory.post("/delete_todo/alice/7").status_code == 403 + assert conn.cursor_obj.queries == [] + + +def test_user_can_still_edit_and_delete_their_own_todo(mallory, monkeypatch): + conn = _Conn() + monkeypatch.setattr(todo, "get_db_connection", lambda: conn) + + assert mallory.post("/update_todo/mallory", data={"todo_id": "7", "task_7": "mine"}).status_code == 302 + assert mallory.post("/delete_todo/mallory/7").status_code == 302 + assert len(_writes(conn)) == 2 + + +def test_user_cannot_mark_another_users_todo(mallory, monkeypatch): + conn = _Conn(row=("00:00 - 00:30", "Study", "", "alice")) + monkeypatch.setattr(todo, "get_db_connection", lambda: conn) + response = mallory.post("/todo/mark_done", json={"id": 7, "completed": True}) + assert response.status_code == 403 + assert _writes(conn) == [] + + conn = _Conn(row=(None, "00:00 - 00:30", "alice", "Study", "2000-01-01 00:00:00")) + monkeypatch.setattr(todo, "get_db_connection", lambda: conn) + response = mallory.post("/todo/mark_status", json={"id": 7, "status": "done"}) + assert response.status_code == 403 + assert _writes(conn) == [] + + +def test_user_cannot_run_another_users_assigned_rule(mallory, monkeypatch): + conn = _Conn(row=("Rule enable all traffic",)) + monkeypatch.setattr(todo, "get_db_connection", lambda: conn) + ran = [] + monkeypatch.setattr(todo, "RULE_FUNCTIONS", {"Rule enable all traffic": lambda: ran.append(1)}) + + assert mallory.post("/exec_rules/someone-else").status_code == 403 + assert ran == [] + assert conn.cursor_obj.queries == [] + + +# ---- 3. CSRF -------------------------------------------------------------- + +ADMIN_ACTIONS = [ + "/rules_toggle/enable_all", + "/rules_toggle/disable_all", + "/rules_toggle/stop_all_traffic", + "/rules_toggle/enable_all_traffic", + "/delete_block/1", + "/auto_push", + "/auto_import", +] + + +@pytest.fixture +def admin_client(notesync_app, notesync_client): + _make_user("admin", "boss") + _login(notesync_app, notesync_client, "admin") + return notesync_client + + +@pytest.mark.parametrize("url", ADMIN_ACTIONS) +def test_admin_actions_cannot_be_triggered_by_get(admin_client, url): + # A GET can be fired by an in a blog post or by any link; these + # routes change filtering, so they must only answer POST. + assert admin_client.get(url).status_code == 405 + + +def test_admin_action_still_works_by_post(admin_client, monkeypatch): + called = [] + monkeypatch.setattr( + blocker, + "rule_disable_all", + lambda: (called.append(1), SimpleNamespace(status_code=200))[1], + ) + assert admin_client.post("/rules_toggle/disable_all").status_code == 302 + assert called == [1] + + +@pytest.mark.parametrize( + ("headers", "status"), + [ + ({"Origin": "https://evil.example"}, 403), + ({"Referer": "https://evil.example/page"}, 403), + ({"Origin": "http://localhost"}, 302), + ({"Referer": "http://localhost/suspicious"}, 302), + ({"Origin": "null"}, 302), + ({}, 302), + ], +) +def test_cross_site_writes_are_refused(admin_client, monkeypatch, headers, status): + called = [] + monkeypatch.setattr( + blocker, + "rule_disable_all", + lambda: (called.append(1), SimpleNamespace(status_code=200))[1], + ) + response = admin_client.post("/rules_toggle/disable_all", headers=headers) + assert response.status_code == status + assert bool(called) == (status == 302) + + +def test_cross_site_get_is_not_blocked(notesync_client): + response = notesync_client.get("/auth/login-ui", headers={"Referer": "https://search.example/"}) + assert response.status_code == 200 + assert response.headers["X-Content-Type-Options"] == "nosniff" + + +# ---- 4. note media -------------------------------------------------------- + + +def _public_media(owner_id, filename, content_type, data=b""): + now = datetime(2026, 11, 1) + note = Note(id=f"n-{filename}", user_id=owner_id, text="x", is_pinned=False, created_at=now, updated_at=now) + note.tags.append(Tag(id=f"t-{filename}", user_id=owner_id, name="public")) + db.session.add(note) + media = Media( + id=f"m-{filename}", + note_id=note.id, + user_id=owner_id, + kind="file", + filename=filename, + content_type=content_type, + checksum="sha256:x", + data=data, + created_at=now, + ) + db.session.add(media) + db.session.commit() + return media.id + + +@pytest.mark.parametrize( + ("filename", "content_type"), + [ + ("a.html", "text/html"), + ("a.html", "TEXT/HTML; charset=utf-8"), + ("a.svg", "image/svg+xml"), + ("a.xml", "application/xml"), + ("a.bin", ""), + ], +) +def test_scriptable_note_media_is_downloaded_not_rendered(notesync_app, notesync_client, filename, content_type): + _make_user("v1", "victim") + _login(notesync_app, notesync_client, "v1") + media_id = _public_media("attacker", filename, content_type) + + response = notesync_client.get(f"/notes/media/{media_id}") + + assert response.status_code == 200 + assert response.mimetype == "application/octet-stream" + assert response.headers["Content-Disposition"].startswith("attachment") + assert response.headers["X-Content-Type-Options"] == "nosniff" + + +@pytest.mark.parametrize( + ("filename", "content_type", "served"), + [("a.png", "image/png", "image/png"), ("a.m4a", "audio/x-m4a", "audio/mp4"), ("a.mp4", "video/mp4", "video/mp4")], +) +def test_real_media_still_displays_inline(notesync_app, notesync_client, filename, content_type, served): + _make_user("v1", "victim") + _login(notesync_app, notesync_client, "v1") + media_id = _public_media("attacker", filename, content_type, data=b"\x89PNG") + + response = notesync_client.get(f"/notes/media/{media_id}") + + assert response.mimetype == served + assert response.headers["Content-Disposition"].startswith("inline") + + +def test_html_upload_through_the_notes_page_is_not_rendered(notesync_app, notesync_client): + _make_user("v1", "victim") + _login(notesync_app, notesync_client, "v1") + notesync_client.post( + "/notes/upload", + data={"text": "x", "media": (io.BytesIO(b""), "a.html", "text/html")}, + content_type="multipart/form-data", + ) + response = notesync_client.get(f"/notes/media/{Media.query.one().id}") + assert response.mimetype == "application/octet-stream" + + +# ---- 5. /auth/callback ---------------------------------------------------- + + +def test_auth_callback_does_not_reflect_html(notesync_client): + payload = "" + response = notesync_client.get("/auth/callback", query_string={"code": payload}) + + assert response.status_code == 200 + assert response.mimetype == "text/plain" + assert response.headers["X-Content-Type-Options"] == "nosniff" + assert payload in response.get_data(as_text=True) + + missing = notesync_client.get("/auth/callback") + assert missing.status_code == 400 + assert missing.mimetype == "text/plain" diff --git a/tests/test_suspicious.py b/tests/test_suspicious.py index 9bb3602..3c79326 100644 --- a/tests/test_suspicious.py +++ b/tests/test_suspicious.py @@ -150,7 +150,7 @@ def close(self): conn = SimpleConn() monkeypatch.setattr(suspicious, "get_db_connection", lambda: conn) - resp = admin_session.get("/delete_block/10") + resp = admin_session.post("/delete_block/10") assert resp.status_code == 302 assert any("DELETE FROM block_list" in sql for sql, _ in conn.cursor_obj.executed) diff --git a/tests/test_todo.py b/tests/test_todo.py index fd00ef3..eb9ae3f 100644 --- a/tests/test_todo.py +++ b/tests/test_todo.py @@ -60,6 +60,15 @@ def close(self): def _login_session(client, monkeypatch): monkeypatch.setattr(auth, "decode_token", lambda token: {"sub": "user"}) + # The todo routes only act for the owner or an admin. Tests that don't set + # their own current user run as an admin; the owner/forbidden cases are + # covered in tests/test_security_fixes.py. + if todo.get_current_username is auth.get_current_username: + monkeypatch.setattr( + todo, + "get_current_username", + lambda: SimpleNamespace(id="u1", username="alice", role="admin"), + ) with client.session_transaction() as sess: sess["access_token"] = "token" @@ -120,7 +129,7 @@ def test_done_todo_updates_status(client, monkeypatch): # Now 12:15, slot ends 13:00: manual check before end, no default status. _freeze_time(monkeypatch, 12, 15) - conn = FakeConnection(rows=[("12:00 - 13:00", "Task", "")]) + conn = FakeConnection(rows=[("12:00 - 13:00", "Task", "", "alice")]) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) monkeypatch.setattr(todo, "flash", lambda *a, **k: None) _login_session(client, monkeypatch) @@ -140,7 +149,7 @@ def test_done_todo_no_default_status_within_grace(client, monkeypatch): # Now 12:15, slot ended 12:00: inside the 30-min grace window the task is # auto-completed but the status stays empty so the user can still choose. _freeze_time(monkeypatch, 12, 15) - conn = FakeConnection(rows=[("11:00 - 12:00", "Math homework", "")]) + conn = FakeConnection(rows=[("11:00 - 12:00", "Math homework", "", "alice")]) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) monkeypatch.setattr(todo, "flash", lambda *a, **k: None) _login_session(client, monkeypatch) @@ -164,7 +173,7 @@ def test_done_todo_auto_complete_true_gets_default_status(client, monkeypatch): # Now 12:15, slot ended 11:40: grace (ends 12:10) is over. _freeze_time(monkeypatch, 12, 15) - conn = FakeConnection(rows=[("11:00 - 11:40", "Math homework", "")]) + conn = FakeConnection(rows=[("11:00 - 11:40", "Math homework", "", "alice")]) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) monkeypatch.setattr(todo, "flash", lambda *a, **k: None) _login_session(client, monkeypatch) @@ -183,7 +192,7 @@ def test_done_todo_defaults_to_mostly_done_after_grace(client, monkeypatch): from .conftest import FakeConnection _freeze_time(monkeypatch, 12, 15) - conn = FakeConnection(rows=[("11:00 - 11:40", "Math homework", "")]) + conn = FakeConnection(rows=[("11:00 - 11:40", "Math homework", "", "alice")]) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) monkeypatch.setattr(todo, "flash", lambda *a, **k: None) _login_session(client, monkeypatch) @@ -201,7 +210,7 @@ def test_done_todo_defaults_to_skipped_for_sleep_task(client, monkeypatch): from .conftest import FakeConnection _freeze_time(monkeypatch, 12, 15) - conn = FakeConnection(rows=[("11:00 - 11:40", "Sleep early", "")]) + conn = FakeConnection(rows=[("11:00 - 11:40", "Sleep early", "", "alice")]) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) monkeypatch.setattr(todo, "flash", lambda *a, **k: None) _login_session(client, monkeypatch) @@ -220,7 +229,7 @@ def test_done_todo_keeps_existing_status_on_auto_complete(client, monkeypatch): # Grace is over but the user already chose a status: never overwrite it. _freeze_time(monkeypatch, 12, 15) - conn = FakeConnection(rows=[("11:00 - 11:40", "Math homework", "done")]) + conn = FakeConnection(rows=[("11:00 - 11:40", "Math homework", "done", "alice")]) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) monkeypatch.setattr(todo, "flash", lambda *a, **k: None) _login_session(client, monkeypatch) diff --git a/tests/test_todo_routes.py b/tests/test_todo_routes.py index 0261544..bd9f756 100644 --- a/tests/test_todo_routes.py +++ b/tests/test_todo_routes.py @@ -48,6 +48,15 @@ def close(self): def _login_session(client, monkeypatch): monkeypatch.setattr(auth, "decode_token", lambda token: {"sub": "user"}) + # The todo routes only act for the owner or an admin. Tests that don't set + # their own current user run as an admin; the owner/forbidden cases are + # covered in tests/test_security_fixes.py. + if todo.get_current_username is auth.get_current_username: + monkeypatch.setattr( + todo, + "get_current_username", + lambda: SimpleNamespace(id="u1", username="alice", role="admin"), + ) with client.session_transaction() as sess: sess["access_token"] = "token" @@ -156,7 +165,7 @@ def test_done_todo_not_found(client, monkeypatch): def test_done_todo_invalid_time_slot(client, monkeypatch): - cursor = SeqCursor(fetchone_values=[("badslot", "Task", "")]) + cursor = SeqCursor(fetchone_values=[("badslot", "Task", "", "alice")]) conn = SeqConnection(cursor) monkeypatch.setattr(todo, "get_db_connection", lambda: conn) _login_session(client, monkeypatch) @@ -221,7 +230,7 @@ def test_mark_todo_status_invalid_status(client, monkeypatch): def test_mark_todo_status_success(client, monkeypatch): cursor = SeqCursor( fetchone_values=[ - (None, "00:00 - 00:30", "bob", "Study", "2000-01-01 00:00:00"), + (None, "00:00 - 00:30", "alice", "Study", "2000-01-01 00:00:00"), ], ) conn = SeqConnection(cursor) @@ -255,7 +264,7 @@ def release(self): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="user", role="user"), + lambda: SimpleNamespace(id="u1", username="user", role="user"), ) _login_session(client, monkeypatch) @@ -285,7 +294,7 @@ def release(self): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="user", role="user"), + lambda: SimpleNamespace(id="u1", username="user", role="user"), ) # Mock time to be within 16:00 - 18:00 From 489d23b1551469a69fc872e0553ae80e8976409c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 12 Nov 2026 19:45:36 +0000 Subject: [PATCH 2/3] Refuse state-changing requests with a hostless Origin Origin: null (sandboxed frames and other opaque origins) parsed to an empty host and was let through, also skipping the Referer fallback. Any Origin or Referer that doesn't name our own host is now refused; requests with neither header still pass. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012k19dCKBK4J2UdDMJd5gLv --- src/safe_family/app.py | 5 +++-- tests/test_security_fixes.py | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/safe_family/app.py b/src/safe_family/app.py index 86a3483..859c781 100644 --- a/src/safe_family/app.py +++ b/src/safe_family/app.py @@ -42,8 +42,9 @@ def reject_cross_site_writes() -> tuple[Response, int] | None: source = request.headers.get("Origin") or request.headers.get("Referer") if not source: return None - host = urlsplit(source).netloc - if host and host != request.host: + # A header with no host (e.g. "Origin: null" from a sandboxed frame) is an + # origin we can't vouch for, so it is refused like any other foreign one. + if urlsplit(source).netloc != request.host: return jsonify({"error": "cross-site request blocked"}), 403 return None diff --git a/tests/test_security_fixes.py b/tests/test_security_fixes.py index 2da899a..d297daf 100644 --- a/tests/test_security_fixes.py +++ b/tests/test_security_fixes.py @@ -288,7 +288,8 @@ def test_admin_action_still_works_by_post(admin_client, monkeypatch): ({"Referer": "https://evil.example/page"}, 403), ({"Origin": "http://localhost"}, 302), ({"Referer": "http://localhost/suspicious"}, 302), - ({"Origin": "null"}, 302), + ({"Origin": "null"}, 403), + ({"Origin": "null", "Referer": "http://localhost/suspicious"}, 403), ({}, 302), ], ) From a0671990ea516437edbbc3107abae824b679de3f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:43:03 +0000 Subject: [PATCH 3/3] Add crop-before-upload to the lotto photo upload form A tray photo usually includes the edge of neighbouring trays, whose tickets would be counted twice. After choosing photos, each one now shows a preview with a crop frame: drag to draw it, drag inside to move, drag a corner to resize, "Use whole photo" to reset. On upload, framed photos are replaced by a JPEG of just that region cut from the full-resolution image (capped at 16 MP for the iOS canvas limit); unframed photos are uploaded untouched. Runs entirely in the browser after the existing HEIC conversion, so the server is unchanged. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012k19dCKBK4J2UdDMJd5gLv --- docs/lotto-training.md | 7 + src/safe_family/static/css/styles.css | 25 +++ src/safe_family/templates/lotto/lotto.html | 177 ++++++++++++++++++++- tests/test_lotto.py | 6 + 4 files changed, 214 insertions(+), 1 deletion(-) diff --git a/docs/lotto-training.md b/docs/lotto-training.md index 5837b67..9c18da0 100644 --- a/docs/lotto-training.md +++ b/docs/lotto-training.md @@ -101,6 +101,13 @@ Open `/lotto` on your phone, tap **Choose / take photos**, then **Upload**. * The ceiling lights make round white reflections on the glass. Tilt the phone a little so they don't sit on a row of price corners. A little glare is OK: real photos have it, so the model must learn it. +* **Crop before upload.** A tray photo usually catches the edge of the + neighbouring trays, and their tickets must not be counted twice. After you + choose photos, each one shows a preview: drag a frame around the tray, drag + inside the frame to move it, drag a corner to resize, or press **Use whole + photo** to undo. Only the framed part is uploaded, cut from the + full-resolution photo, so the price corners stay as sharp as in the original. + Photos you don't frame are uploaded untouched. * **HEIC (iPhone's default format) is converted to JPEG in the browser** before upload, because the training scripts can't read HEIC. iPhone Safari usually sends JPEG anyway. A browser that can't decode HEIC (e.g. Chrome on diff --git a/src/safe_family/static/css/styles.css b/src/safe_family/static/css/styles.css index ffff6c0..3e47e7d 100644 --- a/src/safe_family/static/css/styles.css +++ b/src/safe_family/static/css/styles.css @@ -1989,3 +1989,28 @@ td form button { margin: 0; padding: 8px 16px; } + +.lotto-crops { + display: flex; + flex-direction: column; + gap: 16px; +} + +.lotto-crop-editor { + display: flex; + flex-direction: column; + gap: 6px; +} + +/* Height is capped so there is always page left to scroll with a finger: + touches on the canvas itself draw the crop frame instead of scrolling. */ +.lotto-crop-editor canvas { + display: block; + align-self: flex-start; + max-width: 100%; + max-height: 70vh; + touch-action: none; + cursor: crosshair; + border-radius: var(--sf-radius-sm); + background: var(--sf-surface-3); +} diff --git a/src/safe_family/templates/lotto/lotto.html b/src/safe_family/templates/lotto/lotto.html index fce712d..3cc81f5 100644 --- a/src/safe_family/templates/lotto/lotto.html +++ b/src/safe_family/templates/lotto/lotto.html @@ -15,7 +15,9 @@

One photo per tray (not the whole case: its price corners come out too small), from straight above, the tray filling the frame, full resolution. Tilt the phone a little if a ceiling light reflects on the glass. You can pick several photos at once. Upload whenever you like: photos wait in - To label until you have time, even for weeks.

+ To label until you have time, even for weeks.
+ Crop before upload: after choosing, drag a frame around the tray on each preview to cut off the + neighbouring trays. Only the framed part is uploaded.

@@ -23,6 +25,7 @@
+
@@ -186,6 +189,7 @@ msg.hidden = true; if (!heif.length) { chosen.textContent = files.length === 1 ? files[0].name : (files.length ? `${files.length} files chosen` : 'No photos chosen'); + await buildEditors(files); return; } uploadBtn.disabled = true; @@ -205,6 +209,177 @@ 'Upload them from Safari, or set iPhone Settings > Camera > Formats > Most Compatible.'; } uploadBtn.disabled = n === 0; + await buildEditors([...kept.files]); + }); + + // ---- Crop before upload ------------------------------------------- + // Each chosen photo gets a preview with a crop frame. On submit, photos + // with a frame are replaced by a JPEG of just that region, cut from the + // full-resolution image; photos without one are uploaded untouched. + const form = photos.closest('form'); + const cropsEl = document.getElementById('lotto-crops'); + const MAX_EDITORS = 12; + const MIN_SIDE = 0.05; // a frame smaller than 5% of a side is a slip, not a crop + const HANDLE = 22; // corner grab size, CSS px (finger-sized) + let editors = []; + + const isFull = r => r.x <= 0.001 && r.y <= 0.001 && r.w >= 0.998 && r.h >= 0.998; + const clamp = (v, lo, hi) => Math.min(Math.max(v, lo), hi); + + function drawEditor(ed) { + const { canvas, img, rect } = ed; + const ctx = canvas.getContext('2d'); + const W = canvas.width, H = canvas.height; + ctx.drawImage(img, 0, 0, W, H); + const full = isFull(rect); + if (!full) { + const x = rect.x * W, y = rect.y * H, w = rect.w * W, h = rect.h * H; + ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'; + ctx.fillRect(0, 0, W, y); + ctx.fillRect(0, y + h, W, H - y - h); + ctx.fillRect(0, y, x, h); + ctx.fillRect(x + w, y, W - x - w, h); + const k = W / canvas.getBoundingClientRect().width || 1; + ctx.lineWidth = 3 * k; + ctx.strokeStyle = '#ff7a2e'; + ctx.strokeRect(x, y, w, h); + ctx.fillStyle = '#ff7a2e'; + const hs = 12 * k; + [[x, y], [x + w, y], [x, y + h], [x + w, y + h]].forEach(([cx, cy]) => ctx.fillRect(cx - hs / 2, cy - hs / 2, hs, hs)); + } + const pw = Math.round(rect.w * img.naturalWidth), ph = Math.round(rect.h * img.naturalHeight); + ed.info.textContent = full + ? `Whole photo (${img.naturalWidth}×${img.naturalHeight}). Drag on the photo to crop.` + : `Cropped to ${pw}×${ph} px (${Math.round(rect.w * rect.h * 100)}% of the photo).`; + ed.reset.hidden = full; + } + + function attachPointer(ed) { + const { canvas } = ed; + const frac = e => { + const b = canvas.getBoundingClientRect(); + return { x: clamp((e.clientX - b.left) / b.width, 0, 1), y: clamp((e.clientY - b.top) / b.height, 0, 1) }; + }; + let drag = null; + canvas.addEventListener('pointerdown', (e) => { + e.preventDefault(); + canvas.setPointerCapture(e.pointerId); + const p = frac(e), r = ed.rect, b = canvas.getBoundingClientRect(); + const hx = HANDLE / b.width, hy = HANDLE / b.height; + const corners = [[r.x, r.y], [r.x + r.w, r.y], [r.x, r.y + r.h], [r.x + r.w, r.y + r.h]]; + const ci = isFull(r) ? -1 : corners.findIndex(([cx, cy]) => Math.abs(p.x - cx) < hx && Math.abs(p.y - cy) < hy); + if (ci >= 0) { + // Resize: the opposite corner stays put. + const [ax, ay] = corners[3 - ci]; + drag = { mode: 'anchor', ax, ay }; + } else if (!isFull(r) && p.x > r.x && p.x < r.x + r.w && p.y > r.y && p.y < r.y + r.h) { + drag = { mode: 'move', start: p, orig: { ...r } }; + } else { + drag = { mode: 'anchor', ax: p.x, ay: p.y, fresh: true, before: { ...r } }; + } + }); + canvas.addEventListener('pointermove', (e) => { + if (!drag) return; + const p = frac(e); + if (drag.mode === 'move') { + const o = drag.orig; + ed.rect = { ...o, x: clamp(o.x + p.x - drag.start.x, 0, 1 - o.w), y: clamp(o.y + p.y - drag.start.y, 0, 1 - o.h) }; + } else { + ed.rect = { x: Math.min(p.x, drag.ax), y: Math.min(p.y, drag.ay), w: Math.abs(p.x - drag.ax), h: Math.abs(p.y - drag.ay) }; + } + drawEditor(ed); + }); + const end = () => { + if (!drag) return; + if (ed.rect.w < MIN_SIDE || ed.rect.h < MIN_SIDE) { + // Too small to be a real crop: a tap keeps what was there before. + ed.rect = drag.fresh ? drag.before : { x: 0, y: 0, w: 1, h: 1 }; + } + drag = null; + drawEditor(ed); + }; + canvas.addEventListener('pointerup', end); + canvas.addEventListener('pointercancel', end); + } + + async function buildEditors(files) { + editors.forEach(ed => URL.revokeObjectURL(ed.url)); + editors = []; + cropsEl.innerHTML = ''; + for (const file of files.slice(0, MAX_EDITORS)) { + const url = URL.createObjectURL(file); + const img = new Image(); + img.src = url; + try { await img.decode(); } catch (e) { URL.revokeObjectURL(url); continue; } + const box = document.createElement('div'); + box.className = 'lotto-crop-editor'; + const title = document.createElement('div'); + title.className = 'lotto-dim'; + title.textContent = file.name; + const canvas = document.createElement('canvas'); + const scale = Math.min(1, 1400 / Math.max(img.naturalWidth, img.naturalHeight)); + canvas.width = Math.round(img.naturalWidth * scale); + canvas.height = Math.round(img.naturalHeight * scale); + const row = document.createElement('div'); + row.className = 'lotto-actions'; + const info = document.createElement('span'); + info.className = 'lotto-dim'; + const reset = document.createElement('button'); + reset.type = 'button'; + reset.className = 'btn btn-secondary lotto-btn'; + reset.textContent = 'Use whole photo'; + row.append(info, reset); + box.append(title, canvas, row); + cropsEl.append(box); + const ed = { file, img, url, canvas, info, reset, rect: { x: 0, y: 0, w: 1, h: 1 } }; + reset.addEventListener('click', () => { ed.rect = { x: 0, y: 0, w: 1, h: 1 }; drawEditor(ed); }); + attachPointer(ed); + editors.push(ed); + drawEditor(ed); + } + if (files.length > MAX_EDITORS) { + const note = document.createElement('p'); + note.className = 'lotto-help'; + note.textContent = `Only the first ${MAX_EDITORS} photos can be cropped here; the rest upload whole.`; + cropsEl.append(note); + } + } + + async function cropFile(ed) { + const { img, rect, file } = ed; + const sx = Math.round(rect.x * img.naturalWidth), sy = Math.round(rect.y * img.naturalHeight); + const sw = Math.max(1, Math.round(rect.w * img.naturalWidth)), sh = Math.max(1, Math.round(rect.h * img.naturalHeight)); + const scale = Math.min(1, Math.sqrt(MAX_PIXELS / (sw * sh))); + const canvas = document.createElement('canvas'); + canvas.width = Math.round(sw * scale); + canvas.height = Math.round(sh * scale); + canvas.getContext('2d').drawImage(img, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height); + const blob = await new Promise(resolve => canvas.toBlob(resolve, 'image/jpeg', 0.92)); + if (!blob || blob.size < 1000) throw new Error('encode failed'); + const name = file.name.replace(/\.[^.]+$/, '') + '-crop.jpg'; + return new File([blob], name, { type: 'image/jpeg', lastModified: file.lastModified }); + } + + form.addEventListener('submit', async (e) => { + const cropped = editors.filter(ed => !isFull(ed.rect)); + if (!cropped.length) return; // nothing to crop: normal upload + e.preventDefault(); + uploadBtn.disabled = true; + chosen.textContent = `Cropping ${cropped.length} photo(s)…`; + const out = new DataTransfer(); + const failed = []; + for (const file of photos.files) { + const ed = cropped.find(c => c.file === file); + if (!ed) { out.items.add(file); continue; } + try { out.items.add(await cropFile(ed)); } catch (err) { out.items.add(file); failed.push(file.name); } + } + if (failed.length && !confirm(`Could not crop ${failed.join(', ')}. Upload the whole photo instead?`)) { + uploadBtn.disabled = false; + chosen.textContent = `${photos.files.length} photo(s) ready`; + return; + } + photos.files = out.files; + form.submit(); }); })(); diff --git a/tests/test_lotto.py b/tests/test_lotto.py index c6a658f..6c70646 100644 --- a/tests/test_lotto.py +++ b/tests/test_lotto.py @@ -586,3 +586,9 @@ def test_lotto_styles_leave_store_calculator_rows_alone(): assert ".lotto-row" not in css calculator = (root / "templates" / "miscellaneous" / "store_calculator.html").read_text() assert 'class="lotto-row' in calculator + + +def test_upload_form_offers_crop_before_upload(user_client): + page = user_client.get("/lotto").get_data(as_text=True) + assert 'id="lotto-crops"' in page + assert "Crop before upload" in page