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/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/app.py b/src/safe_family/app.py index cab279d..859c781 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,33 @@ 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 + # 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 + + +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 +117,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/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/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 %}
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.