From 5d2e001f62fd93bb10f49e9c9709b16f5809674d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 14:02:19 +0000 Subject: [PATCH 1/2] Open sign-up with admin approval; fix OAuth linking, usernames, root container Registration: open again by default. A new account is unapproved (users.is_approved) and only gets its own todo list, notes and draft posts. Only approved accounts and the admin can use the rule buttons that change the network filter (disable_ai, exec_rules), trigger email/Discord notifications, or publish public blog posts. The admin approves accounts in a new Accounts card on MGMT. ALLOW_REGISTRATION=False still closes sign-up. OAuth: Google/GitHub sign-in only uses a provider-verified email (GitHub no longer falls back to an unverified address; Google must report email_verified). An existing account is matched by email only if it was itself created by a provider, so a later Google login can't land in an account someone pre-registered with the victim's address and their own password. Usernames: Google/GitHub display names that are taken get a suffix (Alex-2), because todo lists are keyed by username. migrate.py adds a unique index on users.username, skipped with a notice while duplicates exist. Container: the app runs as an unprivileged user (APP_UID/APP_GID, default 1000) instead of root, and the SSH mount is SSH_KEY_DIR (default ~/.ssh) at /home/app/.ssh so a dedicated deploy key can be used. migrate.py must be run after deploying: the app now reads users.is_approved. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012k19dCKBK4J2UdDMJd5gLv --- Dockerfile | 24 +- README.md | 42 +- config/settings.py | 9 +- docker-compose.yml | 13 +- scripts/migrate.py | 22 + src/safe_family/core/auth.py | 128 ++++-- src/safe_family/core/models.py | 6 +- .../templates/rules/suspicious_view.html | 27 ++ src/safe_family/todo/todo.py | 36 +- src/safe_family/urls/blocker.py | 4 +- src/safe_family/urls/blog.py | 15 +- src/safe_family/urls/suspicious.py | 13 + src/safe_family/users/users.py | 24 +- tests/test_accounts.py | 388 ++++++++++++++++++ tests/test_auth_oauth.py | 2 +- tests/test_blog.py | 2 +- tests/test_lotto.py | 2 +- tests/test_security_fixes.py | 2 +- tests/test_todo.py | 8 +- tests/test_todo_routes.py | 16 +- 20 files changed, 708 insertions(+), 75 deletions(-) create mode 100644 tests/test_accounts.py diff --git a/Dockerfile b/Dockerfile index 72d4bde..825b235 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,13 +23,31 @@ RUN pip install --upgrade pip && \ # Install Firefox (and its system libraries) for Playwright gas price snapshots. # Firefox, not Chromium: cbc.ca's CDN blocks headless Chromium (ERR_HTTP2_PROTOCOL_ERROR). -RUN playwright install --with-deps firefox +# A shared path (not /root/.cache) so the unprivileged app user can launch it. +ENV PLAYWRIGHT_BROWSERS_PATH=/ms-playwright +RUN playwright install --with-deps firefox && chmod -R a+rX /ms-playwright + +# The app runs as an unprivileged user, not root: a bug that lets someone run +# code in the container then can't read root-only files, install packages or +# change the image. Its uid/gid should match the host user that owns the +# mounted folders (./logs, the AdGuard rules repo, the SSH key folder), so set +# APP_UID / APP_GID in .env to `id -u` / `id -g` if they aren't 1000. +ARG APP_UID=1000 +ARG APP_GID=1000 +# safe.directory: the rules repo is bind-mounted from the host, so tell git it +# is expected at that path. +RUN groupadd --non-unique --gid ${APP_GID} app \ + && useradd --non-unique --create-home --uid ${APP_UID} --gid ${APP_GID} app \ + && git config --system --add safe.directory /app/adguard_rules # Copy the project files -COPY . . +COPY --chown=app:app . . # Create logs directory -RUN mkdir -p logs +RUN mkdir -p logs && chown app:app /app /app/logs + +USER app +ENV HOME=/home/app # Expose the port the app runs on EXPOSE 8000 diff --git a/README.md b/README.md index 5afbd74..9759425 100644 --- a/README.md +++ b/README.md @@ -113,9 +113,31 @@ data instead. ### 3. Key Mounts and Overrides - **Logs**: Backend logs are mirrored to the local `./logs` directory. -- **SSH Keys**: Local `~/.ssh` is mounted read-only to `/root/.ssh` in the `app` container to support Git operations. +- **SSH Keys**: `SSH_KEY_DIR` (default `~/.ssh`) is mounted read-only to `/home/app/.ssh` in the `app` container to support Git operations. Prefer a folder that holds only a deploy key for the rules repository; see [Running as a non-root user](#running-as-a-non-root-user). - **AdGuard Rules**: The directory specified by `HOST_ADGUARD_RULE_PATH` in your `.env` is mounted to allow rule manipulation. +#### Running as a non-root user +The `app` container runs as the unprivileged user `app`, not root. Files it +touches on the host must belong to the same uid/gid: + +```bash +# .env — only needed when `id -u` / `id -g` are not 1000 +APP_UID=1000 +APP_GID=1000 +# A folder with just the rules repo's deploy key, instead of all of ~/.ssh +SSH_KEY_DIR=/home/you/.ssh-safefamily +``` + +- `./logs` and the `HOST_ADGUARD_RULE_PATH` repo must be writable by that user + (`sudo chown -R $(id -u):$(id -g) logs` if an older root-run container + created them). +- Rebuild after changing the uid: `docker-compose up -d --build app`. +- To use a dedicated deploy key: `ssh-keygen -t ed25519 -f ~/.ssh-safefamily/id_ed25519`, + add the `.pub` as a **deploy key with write access** on the rules repository + only, and copy your `known_hosts` into the same folder. A leaked deploy key + can push to that one repository and nothing else. +- Commands that need root inside the container: `docker exec -u root safefamily_app ...`. + ### 4. Useful Commands - **Start / Stop (daily use)**: `docker compose start` / `docker compose stop` - **View Logs**: `docker-compose logs -f app` @@ -344,10 +366,20 @@ Example `DB_PARAMS`: ``` 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. +- Sign-up is open, but a new account is **unapproved**: it gets its own todo + list, notes and draft blog posts, and nothing else. Approve family members + under **MGMT → Accounts**. Only approved accounts (and the admin) can use the + rule buttons that change the network filter, trigger email/Discord + notifications, or publish public blog posts. +- `ALLOW_REGISTRATION`: set to `False` to refuse new accounts entirely (register + form, `POST /auth/register`, and first-time Google/GitHub sign-in). Default + `True`. +- Google/GitHub sign-in only uses an email the provider has verified, and only + matches an existing account by email if that account was itself created by + Google/GitHub sign-in. An account made with the register form is reached with + its password only. +- Usernames are unique. A Google/GitHub display name that is already taken gets + a suffix (`Alex-2`). Notesync: - `NOTESYNC_API_KEY` diff --git a/config/settings.py b/config/settings.py index dc5e5ad..eb2a399 100644 --- a/config/settings.py +++ b/config/settings.py @@ -114,10 +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" + # Sign-up is open by default: a new account only gets its own todo list, + # notes and draft posts until the admin approves it on the MGMT page (see + # User.is_approved). Set this to "False" to refuse new accounts entirely + # (form, API and first-time Google/GitHub sign-in). + ALLOW_REGISTRATION = os.environ.get("ALLOW_REGISTRATION", "True") == "True" # Countdown page settings (date in YYYY-MM-DD) COUNTDOWN_DATE = os.environ.get("COUNTDOWN_DATE", "") diff --git a/docker-compose.yml b/docker-compose.yml index 033ce48..db60778 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -15,7 +15,12 @@ services: - ./deploy/init_db:/docker-entrypoint-initdb.d app: - build: . + build: + context: . + args: + # Match the host user that owns ./logs, the rules repo and the SSH keys. + APP_UID: ${APP_UID:-1000} + APP_GID: ${APP_GID:-1000} container_name: safefamily_app restart: always depends_on: @@ -25,8 +30,10 @@ services: - ./logs:/app/logs # Mount your local AdGuard repo directory - ${HOST_ADGUARD_RULE_PATH}:/app/adguard_rules - # Mount SSH keys for git push operations - - ~/.ssh:/root/.ssh:ro + # SSH key for pushing the rules repo, read-only, for the unprivileged app + # user. Point SSH_KEY_DIR at a folder holding ONLY a deploy key for that + # one repo (plus known_hosts/config) instead of your whole ~/.ssh. + - ${SSH_KEY_DIR:-~/.ssh}:/home/app/.ssh:ro environment: - PYTHONUNBUFFERED=1 - GUNICORN_WORKERS=4 diff --git a/scripts/migrate.py b/scripts/migrate.py index 9f92e74..1977e5f 100644 --- a/scripts/migrate.py +++ b/scripts/migrate.py @@ -12,6 +12,28 @@ from src.safe_family.core.extensions import get_db_connection MIGRATIONS = [ + # Admin approval for accounts (see User.is_approved). Accounts that exist + # when this first runs stay approved; accounts created afterwards start + # unapproved. Both statements are safe to re-run. + """ + ALTER TABLE users ADD COLUMN IF NOT EXISTS is_approved BOOLEAN NOT NULL DEFAULT TRUE + """, + """ + ALTER TABLE users ALTER COLUMN is_approved SET DEFAULT FALSE + """, + # The todo lists are keyed by username, so usernames must be unique. Skipped + # (with a notice) while duplicates exist: rename them, then re-run. + """ + DO $$ + BEGIN + IF EXISTS (SELECT 1 FROM users GROUP BY username HAVING count(*) > 1) THEN + RAISE NOTICE 'users.username has duplicates: unique index NOT created'; + ELSE + CREATE UNIQUE INDEX IF NOT EXISTS uq_users_username ON users (username); + END IF; + END + $$ + """, # Speeds up per-user history scans (week strip / activity heatmap on /todo) # and the existing per-day lookups. """ diff --git a/src/safe_family/core/auth.py b/src/safe_family/core/auth.py index fcbb138..adf5796 100644 --- a/src/safe_family/core/auth.py +++ b/src/safe_family/core/auth.py @@ -46,6 +46,79 @@ OAUTH_STATE_TTL_SECONDS = 600 MIN_PASSWORD_LENGTH = 8 REGISTRATION_CLOSED = "Registration is closed. Ask the admin to add you." +NOT_APPROVED = "Your account is waiting for the admin's approval, so this is not available yet." +EMAIL_TAKEN = ( + "An account with this email already exists. Log in with your username and " + "password instead." +) +EMAIL_UNVERIFIED = "Your email address is not verified with this provider, so it can't be used to sign in." + + +def is_family(user: User | None) -> bool: + """Return True for the admin and for accounts the admin has approved. + + Sign-up is open, so being logged in proves nothing about who you are. + Anything that affects the household (the network filter, notifications, + public posts) must check this, not just login. + """ + return user is not None and (user.role == "admin" or bool(getattr(user, "is_approved", False))) + + +def family_required(view_func: Callable) -> Callable: + """Require a logged-in, admin-approved account for a view.""" + + @wraps(view_func) + def wrapped(*args: object, **kwargs: object) -> object: + if not is_family(get_current_username()): + flash(NOT_APPROVED, "warning") + return redirect("/") + return view_func(*args, **kwargs) + + return login_required(wrapped) + + +def unique_username(wanted: str) -> str: + """Return ``wanted``, or ``wanted-2``, ``wanted-3``... if it is taken. + + Todo lists are keyed by username, so two accounts must never share one. + Google/GitHub display names are not unique ("Alex"), hence the suffix. + """ + base = (wanted or "").strip() or "user" + candidate, n = base, 1 + while User.get_user_by_username(username=candidate) is not None: + n += 1 + candidate = f"{base}-{n}" + return candidate + + +def _created_by_oauth(user: User) -> bool: + """Return True for accounts first created by a Google/GitHub sign-in. + + Those get the provider's numeric account id as their id; password sign-ups + get a UUID. Only provider-created accounts have an email the provider + verified, so only they may be matched by email. + """ + return str(user.id).isdigit() + + +def find_oauth_user(provider_id: str, email: str, *, email_verified: bool) -> tuple[User | None, str | None]: + """Find the account for a Google/GitHub sign-in: (user, refusal message). + + The provider's own account id always matches. An email only matches when + the provider verified it AND the existing account was itself created by a + provider. An email typed into the sign-up form was never verified, so + letting a later Google/GitHub login land in such an account would hand it + to whoever registered first with someone else's address. + """ + user = User.query.filter_by(id=provider_id).first() + if user is not None: + return user, None + existing = User.query.filter_by(email=email).first() + if existing is None: + return None, None + if email_verified and _created_by_oauth(existing): + return existing, None + return None, EMAIL_TAKEN def require_api_key(view_func: Callable) -> Callable: @@ -293,6 +366,8 @@ def session_login(): session["refresh_token"] = tokens.get("refresh_token") flash("Login successful!", "success") + if not is_family(get_current_username()): + flash(NOT_APPROVED, "info") return redirect("/") @@ -641,29 +716,24 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl if emails_response.status_code == HTTP_OK: emails = emails_response.json() - email = user_info.get("email") - if not email and emails: - primary_verified = [ - entry for entry in emails if entry.get("primary") and entry.get("verified") - ] - verified = [entry for entry in emails if entry.get("verified")] - selection = ( - primary_verified[0] - if primary_verified - else verified[0] - if verified - else emails[0] - ) - email = selection.get("email") - if not email: + # Only an address GitHub has verified identifies the person. An + # unverified one can be typed in by anyone, so it is never used. + verified = [entry for entry in emails if entry.get("verified") and entry.get("email")] + primary = [entry for entry in verified if entry.get("primary")] + email_verified = bool(verified) + if verified: + email = (primary or verified)[0]["email"] + else: + # GitHub's own per-account placeholder: nobody else can hold it. login_name = user_info.get("login", "github_user") email = f"{login_name}@users.noreply.github.com" github_id = str(user_info.get("id")) name = user_info.get("name") or user_info.get("login") or email.split("@")[0] - user = User.query.filter_by(id=github_id).first() - if not user: - user = User.query.filter_by(email=email).first() + user, refusal = find_oauth_user(github_id, email, email_verified=email_verified) + if refusal: + flash(refusal, "warning") + return redirect("/auth/login-ui") if not user and not settings.ALLOW_REGISTRATION: flash(REGISTRATION_CLOSED, "warning") @@ -672,7 +742,7 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl if not user: new_user = User( id=github_id, - username=name, + username=unique_username(name), email=email, ) new_user.set_password(secrets.token_urlsafe(48)) @@ -688,11 +758,13 @@ def github_callback(): # noqa: C901, PLR0911, PLR0912, PLR0915 - refactor backl session["access_token"] = create_access_token(identity=user.id) session["refresh_token"] = create_refresh_token(identity=user.id) flash("Login successful!", "success") + if not is_family(get_current_username()): + flash(NOT_APPROVED, "info") return redirect("/") @auth_bp.get("/google/callback") -def google_callback(): +def google_callback(): # noqa: PLR0911 - one early return per refusal """Handle the Google OAuth callback and create the session.""" state = request.args.get("state") state_payload = _read_oauth_state(state) @@ -721,10 +793,14 @@ def google_callback(): ) google_id = id_info["sub"] email = id_info["email"] - name = id_info.get("name", "") - user = User.query.filter_by(id=google_id).first() - if not user: - user = User.query.filter_by(email=email).first() + name = id_info.get("name", "") or email.split("@")[0] + if not id_info.get("email_verified"): + flash(EMAIL_UNVERIFIED, "warning") + return redirect("/auth/login-ui") + user, refusal = find_oauth_user(google_id, email, email_verified=True) + if refusal: + flash(refusal, "warning") + return redirect("/auth/login-ui") if not user and not settings.ALLOW_REGISTRATION: flash(REGISTRATION_CLOSED, "warning") @@ -733,7 +809,7 @@ def google_callback(): if not user: new_user = User( id=google_id, - username=name, + username=unique_username(name), email=email, ) new_user.set_password(secrets.token_urlsafe(48)) @@ -749,6 +825,8 @@ def google_callback(): session["access_token"] = create_access_token(identity=user.id) session["refresh_token"] = create_refresh_token(identity=user.id) flash("Login successful!", "success") + if not is_family(get_current_username()): + flash(NOT_APPROVED, "info") return redirect("/") diff --git a/src/safe_family/core/models.py b/src/safe_family/core/models.py index 7af80a8..b12d198 100644 --- a/src/safe_family/core/models.py +++ b/src/safe_family/core/models.py @@ -13,11 +13,15 @@ class User(db.Model): __tablename__ = "users" - id = db.Column(db.String(), primary_key=True, default=(uuid.uuid4)) + id = db.Column(db.String(), primary_key=True, default=lambda: str(uuid.uuid4())) username = db.Column(db.String(), nullable=False) email = db.Column(db.String(), unique=True, nullable=False) password_hash = db.Column(db.String(256), nullable=False) role = db.Column(db.String(20)) + # Anyone may sign up, but only accounts the admin has approved count as + # family: they may change the shared network filter, send notifications and + # publish public posts. New accounts start unapproved. + is_approved = db.Column(db.Boolean(), nullable=False, default=False) created_at = db.Column(db.DateTime, default=lambda: datetime.now(UTC)) updated_at = db.Column( db.DateTime, diff --git a/src/safe_family/templates/rules/suspicious_view.html b/src/safe_family/templates/rules/suspicious_view.html index 10d4a8b..01c53c8 100644 --- a/src/safe_family/templates/rules/suspicious_view.html +++ b/src/safe_family/templates/rules/suspicious_view.html @@ -7,6 +7,33 @@ 🎟️ Lotto ticket counter Collect and label display photos, export training data, upload predictions. +
+
Accounts
+

Anyone can sign up, but only accounts you approve count as family: they can use + the rule buttons, send notifications and publish public posts. Unapproved accounts only get their own + todo list, notes and draft posts.

+ + + + + + {% for account in accounts %} + + + + + + + {% endfor %} + +
UserEmailStatusAction
{{ account.username }}{{ account.email }}{{ 'Family' if account.is_approved else 'Waiting' }} +
+ + +
+
+
Suspicious Logs for {{ date }} diff --git a/src/safe_family/todo/todo.py b/src/safe_family/todo/todo.py index b7c377d..002ec88 100644 --- a/src/safe_family/todo/todo.py +++ b/src/safe_family/todo/todo.py @@ -19,8 +19,10 @@ from src.safe_family.cli import weekly_metrics from src.safe_family.core.auth import ( + NOT_APPROVED, admin_required, get_current_username, + is_family, login_required, ) from src.safe_family.core.extensions import db, get_db_connection, local_tz @@ -404,7 +406,8 @@ def todo_page(): # noqa: C901, PLR0915 - refactor backlog: split save/view path (today_date, selected_user), ) today_tasks = cur.fetchall() - if request.method == "POST" and message != "": + # Notifications go to the family's inbox and Discord: approved accounts only. + if request.method == "POST" and message != "" and is_family(user): send_email_notification( selected_user, [{"time_slot": t[1], "task": t[2]} for t in today_tasks], @@ -504,8 +507,9 @@ def update_todo(selected_username: str): {"time_slot": r[0], "task": r[1], "completion_status": r[2]} for r in cur.fetchall() ] - send_email_notification(selected_username, tasks) - send_discord_notification(selected_username, tasks) + if is_family(get_current_username()): + send_email_notification(selected_username, tasks) + send_discord_notification(selected_username, tasks) conn.close() flash("Task updated successfully!", "success") return redirect(url_for("todo.todo_page")) @@ -786,16 +790,17 @@ def mark_todo_status(): # noqa: PLR0911 - one early return per validation step (status, True, todo_id), ) conn.commit() - send_discord_notification( - task_owner, - [ - { - "time_slot": time_slot, - "task": task_name, - "completion_status": status, - }, - ], - ) + if is_family(user): + send_discord_notification( + task_owner, + [ + { + "time_slot": time_slot, + "task": task_name, + "completion_status": status, + }, + ], + ) conn.close() return jsonify({"success": True}) except Exception as e: @@ -901,6 +906,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") + # Rules change the household's network filter: approved accounts only. + if not is_family(user): + flash(NOT_APPROVED, "warning") + return redirect(url_for("todo.todo_page")) + # 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: diff --git a/src/safe_family/urls/blocker.py b/src/safe_family/urls/blocker.py index 7ebf614..0b7cfd1 100644 --- a/src/safe_family/urls/blocker.py +++ b/src/safe_family/urls/blocker.py @@ -9,7 +9,7 @@ from flask import Blueprint, flash, redirect from config.settings import settings -from src.safe_family.core.auth import admin_required, login_required +from src.safe_family.core.auth import admin_required, family_required from src.safe_family.utils.constants import HTTP_OK logger = logging.getLogger(__name__) @@ -425,7 +425,7 @@ def rules_toggle_disable(): @rules_toggle_bp.route("/rules_toggle/disable_ai", methods=["POST"]) -@login_required +@family_required def rules_disable_ai(): """Disable AI rules.""" if not DISABLE_AI_LOCK.acquire(blocking=False): diff --git a/src/safe_family/urls/blog.py b/src/safe_family/urls/blog.py index 774584f..c92d3a8 100644 --- a/src/safe_family/urls/blog.py +++ b/src/safe_family/urls/blog.py @@ -16,7 +16,7 @@ from sqlalchemy.orm import selectinload from config.settings import settings -from src.safe_family.core.auth import get_current_username, login_required +from src.safe_family.core.auth import get_current_username, is_family, login_required from src.safe_family.core.extensions import db, local_tz from src.safe_family.core.models import BlogPost, BlogTag from src.safe_family.utils.markdown_render import markdown_excerpt, render_markdown @@ -78,6 +78,17 @@ def _read_form() -> tuple[dict, str | None]: return values, None +def _apply_publish_rule(values: dict, user: object) -> None: + """Keep posts from unapproved accounts as drafts. + + Public posts are readable without logging in, so with open sign-up they + would let anyone publish on this site. + """ + if values["is_public"] and not is_family(user): + values["is_public"] = False + flash("Saved as a draft: publishing needs the admin's approval of your account.", "warning") + + def _get_own_post(post_id: str, user_id: str) -> BlogPost: post = BlogPost.query.filter_by(id=post_id, user_id=user_id).one_or_none() if post is None: @@ -155,6 +166,7 @@ def blog_create(): if error: flash(error, "warning") return _render_editor(None, values, 400) + _apply_publish_rule(values, user) now = datetime.now(UTC).replace(tzinfo=None) post = BlogPost( @@ -230,6 +242,7 @@ def blog_update(post_id: str): flash(error, "warning") return _render_editor(post, values, 400) + _apply_publish_rule(values, user) post.title = values["title"] post.markdown = values["markdown"] post.is_public = values["is_public"] diff --git a/src/safe_family/urls/suspicious.py b/src/safe_family/urls/suspicious.py index 38e6019..e5df21d 100644 --- a/src/safe_family/urls/suspicious.py +++ b/src/safe_family/urls/suspicious.py @@ -11,9 +11,11 @@ render_template, request, ) +from sqlalchemy.exc import SQLAlchemyError from src.safe_family.core.auth import admin_required from src.safe_family.core.extensions import get_db_connection, local_tz +from src.safe_family.users.users import accounts_for_admin from src.safe_family.utils.exceptions import DatabaseConnectionError from src.safe_family.utils.validators import ( MAX_LINES_PER_REQUEST, @@ -26,6 +28,16 @@ split_lines, ) + +def _accounts() -> list: + """Accounts for the approval card; empty if the users table is unreachable.""" + try: + return accounts_for_admin() + except SQLAlchemyError: + logger.exception("Could not list accounts") + return [] + + suspicious_bp = Blueprint("suspicious", __name__) logger = logging.getLogger(__name__) @@ -162,6 +174,7 @@ def view_suspicious(): block_types=block_types, date=date, error=error, + accounts=_accounts(), ) except DatabaseConnectionError as e: logger.exception("Error viewing suspicious") diff --git a/src/safe_family/users/users.py b/src/safe_family/users/users.py index 97ce518..07d59d6 100644 --- a/src/safe_family/users/users.py +++ b/src/safe_family/users/users.py @@ -1,9 +1,10 @@ """User URL routes for Safe Family application.""" -from flask import Blueprint, jsonify, request +from flask import Blueprint, abort, flash, jsonify, redirect, request from flask_jwt_extended import get_jwt, jwt_required -from src.safe_family.core.auth import is_admin_claims +from src.safe_family.core.auth import admin_required, is_admin_claims +from src.safe_family.core.extensions import db from src.safe_family.core.models import User from src.safe_family.core.schemas import UserOut @@ -22,3 +23,22 @@ def get_all_users(): users = User.query.paginate(page=page, per_page=per_page) result = [UserOut.model_validate(user).model_dump() for user in users.items] return jsonify({"users": result}), 200 + + +def accounts_for_admin() -> list[User]: + """Return every account, waiting-for-approval first, for the MGMT page.""" + return User.query.order_by(User.is_approved.asc(), User.username.asc()).all() + + +@user_bp.post("//approve") +@admin_required +def approve_user(user_id: str): + """Mark an account as family, or take that back with approved=0.""" + user = db.session.get(User, user_id) + if user is None: + abort(404) + user.is_approved = request.form.get("approved", "1") == "1" + db.session.commit() + state = "approved as family" if user.is_approved else "no longer approved" + flash(f"{user.username} is {state}.", "success") + return redirect("/suspicious") diff --git a/tests/test_accounts.py b/tests/test_accounts.py new file mode 100644 index 0000000..1ba490e --- /dev/null +++ b/tests/test_accounts.py @@ -0,0 +1,388 @@ +"""Tests for open sign-up with admin approval, OAuth account matching and unique usernames.""" + +from types import SimpleNamespace + +import pytest +from flask import render_template +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 BlogPost, 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, *, approved=False, email=None): + user = User( + id=user_id, + username=username, + email=email or f"{username}@example.com", + role="user", + is_approved=approved, + ) + 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 + + +@pytest.fixture +def newcomer(notesync_app, notesync_client): + """A logged-in account nobody has approved yet.""" + _make_user("11111111-aaaa-bbbb-cccc-000000000001", "newcomer") + _login(notesync_app, notesync_client, "11111111-aaaa-bbbb-cccc-000000000001") + return notesync_client + + +@pytest.fixture +def relative(notesync_app, notesync_client): + """A logged-in account the admin approved.""" + _make_user("fam1", "relative", approved=True) + _login(notesync_app, notesync_client, "fam1") + return notesync_client + + +# ---- sign-up is open, new accounts are unapproved -------------------------- + + +def test_registration_is_open_by_default(): + from config.settings import Settings + + assert Settings.ALLOW_REGISTRATION is True + + +def test_new_account_starts_unapproved(notesync_client): + body = {"username": "anyone", "email": "anyone@example.com", "password": "long-enough-password"} + assert notesync_client.post("/auth/register", json=body).status_code == 201 + user = User.query.filter_by(username="anyone").one() + assert user.is_approved is False + assert not auth.is_family(user) + + +def test_is_family(): + assert auth.is_family(SimpleNamespace(role="admin", is_approved=False)) + assert auth.is_family(SimpleNamespace(role="user", is_approved=True)) + assert not auth.is_family(SimpleNamespace(role="user", is_approved=False)) + assert not auth.is_family(SimpleNamespace(role="user")) + assert not auth.is_family(None) + + +def test_login_tells_unapproved_account_it_is_waiting(notesync_client): + _make_user("11111111-aaaa-bbbb-cccc-000000000002", "waiting") + form = {"username": "waiting", "password": "long-enough-password"} + notesync_client.post("/auth/session-login", data=form) + with notesync_client.session_transaction() as sess: + messages = [text for _category, text in sess.get("_flashes", [])] + assert auth.NOT_APPROVED in messages + + +# ---- what an unapproved account cannot do ---------------------------------- + + +def _watch_disable_ai(monkeypatch): + called = [] + monkeypatch.setattr( + blocker, + "rule_disable_ai", + lambda: (called.append(1), SimpleNamespace(status_code=200))[1], + ) + monkeypatch.setitem(blocker.DISABLE_AI_STATE, "last_run", -1e9) + return called + + +def test_unapproved_account_cannot_change_the_filter(newcomer, monkeypatch): + called = _watch_disable_ai(monkeypatch) + response = newcomer.post("/rules_toggle/disable_ai") + assert response.status_code == 302 + assert called == [] + + +def test_approved_account_can_use_its_rule_button(relative, monkeypatch): + called = _watch_disable_ai(monkeypatch) + relative.post("/rules_toggle/disable_ai") + assert called == [1] + + +def test_disable_ai_still_requires_login(notesync_client, monkeypatch): + called = _watch_disable_ai(monkeypatch) + response = notesync_client.post("/rules_toggle/disable_ai") + assert "/auth/login-ui" in response.headers["Location"] + assert called == [] + + +class _Conn: + def __init__(self): + self.queries = [] + + def cursor(self): + return self + + def execute(self, sql, params=None): + self.queries.append(sql) + + def fetchone(self): + return None + + def fetchall(self): + return [] + + def commit(self): + return None + + def close(self): + return None + + +def test_unapproved_account_cannot_run_rules_or_notify(newcomer, monkeypatch): + conn = _Conn() + sent = [] + monkeypatch.setattr(todo, "get_db_connection", lambda: conn) + monkeypatch.setattr(todo, "send_email_notification", lambda *a, **k: sent.append("email")) + monkeypatch.setattr(todo, "send_discord_notification", lambda *a, **k: sent.append("discord")) + + own_id = "11111111-aaaa-bbbb-cccc-000000000001" + assert newcomer.post(f"/exec_rules/{own_id}").status_code == 302 + assert conn.queries == [] + + # Their own todo list still works, but nothing is sent to the family's inbox. + assert newcomer.post("/update_todo/newcomer", data={"todo_id": "1", "task_1": "x"}).status_code == 302 + assert any(q.strip().startswith("UPDATE") for q in conn.queries) + assert sent == [] + + +def test_approved_account_still_notifies(relative, monkeypatch): + sent = [] + monkeypatch.setattr(todo, "get_db_connection", _Conn) + monkeypatch.setattr(todo, "send_email_notification", lambda *a, **k: sent.append("email")) + monkeypatch.setattr(todo, "send_discord_notification", lambda *a, **k: sent.append("discord")) + relative.post("/update_todo/relative", data={"todo_id": "1", "task_1": "x"}) + assert sent == ["email", "discord"] + + +def test_unapproved_account_cannot_publish_publicly(newcomer, notesync_client): + form = {"title": "Hello", "markdown": "spam", "is_public": "on"} + response = newcomer.post("/blog/new", data=form, follow_redirects=True) + assert "publishing needs the admin" in response.get_data(as_text=True) + post = BlogPost.query.one() + assert post.is_public is False + + newcomer.post(f"/blog/{post.id}/edit", data=form) + assert BlogPost.query.one().is_public is False + + +def test_approved_account_can_publish(relative): + relative.post("/blog/new", data={"title": "Hello", "markdown": "news", "is_public": "on"}) + assert BlogPost.query.one().is_public is True + + +# ---- admin approval --------------------------------------------------------- + + +def test_admin_approves_and_removes_approval(notesync_app, notesync_client): + _make_user("admin", "boss") + target = _make_user("11111111-aaaa-bbbb-cccc-000000000003", "cousin") + _login(notesync_app, notesync_client, "admin") + + response = notesync_client.post(f"/users/{target.id}/approve") + assert response.headers["Location"].endswith("/suspicious") + assert db.session.get(User, target.id).is_approved is True + + notesync_client.post(f"/users/{target.id}/approve", data={"approved": "0"}) + assert db.session.get(User, target.id).is_approved is False + + assert notesync_client.post("/users/nobody/approve").status_code == 404 + assert notesync_client.get(f"/users/{target.id}/approve").status_code == 405 + + +def test_only_admin_can_approve(relative): + target = _make_user("11111111-aaaa-bbbb-cccc-000000000004", "friend") + response = relative.post(f"/users/{target.id}/approve") + assert "/auth/login-ui" in response.headers["Location"] + assert db.session.get(User, target.id).is_approved is False + # ...and not themselves either. + relative.post("/users/fam1/approve", data={"approved": "1"}) + assert db.session.get(User, target.id).is_approved is False + + +def test_mgmt_page_lists_accounts_waiting_first(notesync_app): + from src.safe_family.users.users import accounts_for_admin + + _make_user("fam1", "aaron", approved=True) + _make_user("11111111-aaaa-bbbb-cccc-000000000005", "zoe") + accounts = accounts_for_admin() + assert [a.username for a in accounts] == ["zoe", "aaron"] + + with notesync_app.test_request_context("/suspicious"): + html = render_template( + "rules/suspicious_view.html", + accounts=accounts, suspicious_data=[], block_list=[], filter_rules=[], block_types=[], + page=1, total=0, limit=10, block_page=1, total_blocks=0, block_limit=10, + rule_page=1, total_rules=0, rule_limit=10, date="2026-11-14", error=None, + ) # fmt: skip + card = html.split("mgmt-accounts", 1)[1].split("Suspicious Logs", 1)[0] + assert card.index("zoe") < card.index("aaron") + assert "Waiting" in card + assert "/users/fam1/approve" in card + assert 'name="approved" value="0"' in card + assert 'name="approved" value="1"' in card + + +# ---- OAuth account matching ------------------------------------------------- + + +def test_find_oauth_user_matches_provider_id_first(notesync_app): + known = _make_user("12345", "known") + assert auth.find_oauth_user("12345", "other@example.com", email_verified=False) == (known, None) + + +def test_find_oauth_user_links_verified_email_to_provider_created_account(notesync_app): + google_account = _make_user("109876543210987654321", "me", email="me@gmail.com") + assert auth.find_oauth_user("4242", "me@gmail.com", email_verified=True) == (google_account, None) + # The same address, but GitHub has not verified it: no match. + assert auth.find_oauth_user("4242", "me@gmail.com", email_verified=False) == (None, auth.EMAIL_TAKEN) + + +def test_find_oauth_user_never_lands_in_a_password_account(notesync_app): + # An attacker signed up with the victim's address and a password they know. + _make_user("11111111-aaaa-bbbb-cccc-000000000006", "squatter", email="victim@gmail.com") + assert auth.find_oauth_user("4242", "victim@gmail.com", email_verified=True) == (None, auth.EMAIL_TAKEN) + + +def test_find_oauth_user_unknown_person(notesync_app): + assert auth.find_oauth_user("4242", "new@example.com", email_verified=True) == (None, None) + + +def test_unique_username(notesync_app): + assert auth.unique_username("Alex") == "Alex" + _make_user("1", "Alex") + assert auth.unique_username("Alex") == "Alex-2" + _make_user("2", "Alex-2") + assert auth.unique_username(" Alex ") == "Alex-3" + assert auth.unique_username("") == "user" + + +class _FakeResp: + def __init__(self, payload): + self.status_code = 200 + self._payload = payload + + def json(self): + return self._payload + + +def _github_login(client, monkeypatch, user_info, emails): + 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"})) + monkeypatch.setattr( + auth.requests, + "get", + lambda url, **k: _FakeResp(emails if url.endswith("/emails") else user_info), + ) + response = client.get("/auth/github/callback?state=s&code=c") + with client.session_transaction() as sess: + return response, sess.get("access_token") + + +def test_github_unverified_email_cannot_take_over_an_account(notesync_app, notesync_client, monkeypatch): + victim = _make_user("109876543210987654321", "victim", email="victim@gmail.com", approved=True) + # The attacker's GitHub account lists the victim's address, unverified, and + # also shows it as the public profile email. + response, token = _github_login( + notesync_client, + monkeypatch, + {"id": 666, "email": "victim@gmail.com", "name": "Mallory", "login": "mallory"}, + [{"email": "victim@gmail.com", "primary": True, "verified": False}], + ) + assert response.status_code == 302 + assert token + with notesync_app.app_context(): + from flask_jwt_extended import decode_token + + assert decode_token(token)["sub"] == "666" + attacker = db.session.get(User, "666") + assert attacker.email == "mallory@users.noreply.github.com" + assert attacker.is_approved is False + assert db.session.get(User, victim.id).email == "victim@gmail.com" + + +def test_github_verified_email_of_password_account_is_refused(notesync_client, monkeypatch): + _make_user("11111111-aaaa-bbbb-cccc-000000000007", "local", email="me@example.com") + response, token = _github_login( + notesync_client, + monkeypatch, + {"id": 777, "name": "Me", "login": "me"}, + [{"email": "me@example.com", "primary": True, "verified": True}], + ) + assert response.headers["Location"].endswith("/auth/login-ui") + assert token is None + assert db.session.get(User, "777") is None + + +def test_github_prefers_primary_verified_email_and_unique_username(notesync_client, monkeypatch): + _make_user("fam1", "Alex", approved=True) + _, token = _github_login( + notesync_client, + monkeypatch, + {"id": 888, "name": "Alex", "login": "alex"}, + [ + {"email": "old@example.com", "primary": False, "verified": True}, + {"email": "alex@example.com", "primary": True, "verified": True}, + {"email": "typo@example.com", "primary": False, "verified": False}, + ], + ) + assert token + created = db.session.get(User, "888") + assert created.email == "alex@example.com" + assert created.username == "Alex-2" + + +def _google_login(client, monkeypatch, id_info): + class FakeFlow: + credentials = SimpleNamespace(id_token="token") + + def fetch_token(self, **_kwargs): + return None + + monkeypatch.setattr(auth, "_read_oauth_state", lambda state: {"client": "web"}) + monkeypatch.setattr(auth.Flow, "from_client_config", lambda *a, **k: FakeFlow()) + monkeypatch.setattr(auth.id_token, "verify_oauth2_token", lambda *a, **k: id_info) + response = client.get("/auth/google/callback?state=abc") + with client.session_transaction() as sess: + return response, sess.get("access_token") + + +def test_google_unverified_email_is_refused(notesync_client, monkeypatch): + info = {"sub": "200000000000000000001", "email": "x@corp.example", "email_verified": False, "name": "X"} + response, token = _google_login(notesync_client, monkeypatch, info) + assert response.headers["Location"].endswith("/auth/login-ui") + assert token is None + assert User.query.count() == 0 + + +def test_google_login_does_not_land_in_squatted_password_account(notesync_client, monkeypatch): + _make_user("11111111-aaaa-bbbb-cccc-000000000008", "squatter", email="me@gmail.com") + info = {"sub": "200000000000000000002", "email": "me@gmail.com", "email_verified": True, "name": "Me"} + response, token = _google_login(notesync_client, monkeypatch, info) + assert response.headers["Location"].endswith("/auth/login-ui") + assert token is None + + +def test_google_new_user_gets_unique_username_and_starts_unapproved(notesync_client, monkeypatch): + _make_user("fam1", "Sam Lee", approved=True) + info = {"sub": "200000000000000000003", "email": "sam@gmail.com", "email_verified": True, "name": "Sam Lee"} + _, token = _google_login(notesync_client, monkeypatch, info) + assert token + created = db.session.get(User, "200000000000000000003") + assert created.username == "Sam Lee-2" + assert created.is_approved is False diff --git a/tests/test_auth_oauth.py b/tests/test_auth_oauth.py index d2adcee..6318cd3 100644 --- a/tests/test_auth_oauth.py +++ b/tests/test_auth_oauth.py @@ -200,7 +200,7 @@ def filter_by(self, **_kwargs): monkeypatch.setattr( auth.id_token, "verify_oauth2_token", - lambda *a, **k: {"sub": "g1", "email": "user@example.com", "name": "User"}, + lambda *a, **k: {"sub": "g1", "email": "user@example.com", "email_verified": True, "name": "User"}, ) monkeypatch.setattr(auth.User, "query", FakeQuery(), raising=False) monkeypatch.setattr(auth, "create_access_token", lambda identity: "access") diff --git a/tests/test_blog.py b/tests/test_blog.py index d1bd9c2..367a9e5 100644 --- a/tests/test_blog.py +++ b/tests/test_blog.py @@ -10,7 +10,7 @@ def _make_user(user_id, username): - user = User(id=user_id, username=username, email=f"{username}@example.com", role="user") + user = User(id=user_id, username=username, email=f"{username}@example.com", role="user", is_approved=True) user.set_password("secret") db.session.add(user) db.session.commit() diff --git a/tests/test_lotto.py b/tests/test_lotto.py index 6c70646..69f3bdf 100644 --- a/tests/test_lotto.py +++ b/tests/test_lotto.py @@ -17,7 +17,7 @@ def _make_user(user_id, username): - user = User(id=user_id, username=username, email=f"{username}@example.com", role="user") + user = User(id=user_id, username=username, email=f"{username}@example.com", role="user", is_approved=True) user.set_password("secret") db.session.add(user) db.session.commit() diff --git a/tests/test_security_fixes.py b/tests/test_security_fixes.py index d297daf..3b2af97 100644 --- a/tests/test_security_fixes.py +++ b/tests/test_security_fixes.py @@ -24,7 +24,7 @@ def _make_user(user_id, username): - user = User(id=user_id, username=username, email=f"{username}@example.com", role="user") + user = User(id=user_id, username=username, email=f"{username}@example.com", role="user", is_approved=True) user.set_password("long-enough-password") db.session.add(user) db.session.commit() diff --git a/tests/test_todo.py b/tests/test_todo.py index eb9ae3f..411277c 100644 --- a/tests/test_todo.py +++ b/tests/test_todo.py @@ -261,7 +261,7 @@ def test_mark_status_success_within_grace(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="kid", role="user"), + lambda: SimpleNamespace(username="kid", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -287,7 +287,7 @@ def test_mark_status_rejected_before_slot_end(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="kid", role="user"), + lambda: SimpleNamespace(username="kid", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -309,7 +309,7 @@ def test_mark_status_rejected_when_status_locked(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="kid", role="user"), + lambda: SimpleNamespace(username="kid", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -356,7 +356,7 @@ def test_todo_page_uses_parameterized_date(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="user", role="user"), + lambda: SimpleNamespace(username="user", role="user", is_approved=True), ) monkeypatch.setattr(todo, "render_template", lambda *a, **k: ("ok", 200)) _login_session(client, monkeypatch) diff --git a/tests/test_todo_routes.py b/tests/test_todo_routes.py index bd9f756..1c4a6d4 100644 --- a/tests/test_todo_routes.py +++ b/tests/test_todo_routes.py @@ -72,7 +72,7 @@ def test_todo_page_saves_tasks_and_notifies(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="alice", role="user"), + lambda: SimpleNamespace(username="alice", role="user", is_approved=True), ) monkeypatch.setattr(todo, "generate_time_slots", lambda *a, **k: ["09:00 - 10:00"]) monkeypatch.setattr(todo, "render_template", lambda *a, **k: ("ok", 200)) @@ -119,7 +119,7 @@ def now(cls, tz=None): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="alice", role="user"), + lambda: SimpleNamespace(username="alice", role="user", is_approved=True), ) monkeypatch.setattr(todo, "generate_time_slots", lambda *a, **k: ["09:00 - 10:00"]) monkeypatch.setattr( @@ -189,7 +189,7 @@ def test_split_slot_success(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="alice", role="user"), + lambda: SimpleNamespace(username="alice", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -203,7 +203,7 @@ def test_split_slot_forbidden(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="alice", role="user"), + lambda: SimpleNamespace(username="alice", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -217,7 +217,7 @@ def test_mark_todo_status_invalid_status(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="alice", role="user"), + lambda: SimpleNamespace(username="alice", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -239,7 +239,7 @@ def test_mark_todo_status_success(client, monkeypatch): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(username="alice", role="user"), + lambda: SimpleNamespace(username="alice", role="user", is_approved=True), ) monkeypatch.setattr(todo, "send_discord_notification", lambda *a, **k: None) _login_session(client, monkeypatch) @@ -264,7 +264,7 @@ def release(self): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(id="u1", username="user", role="user"), + lambda: SimpleNamespace(id="u1", username="user", role="user", is_approved=True), ) _login_session(client, monkeypatch) @@ -294,7 +294,7 @@ def release(self): monkeypatch.setattr( todo, "get_current_username", - lambda: SimpleNamespace(id="u1", username="user", role="user"), + lambda: SimpleNamespace(id="u1", username="user", role="user", is_approved=True), ) # Mock time to be within 16:00 - 18:00 From a7d2f34415ca516fdfcefd4e8e7da6143e7539bc Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 14:22:28 +0000 Subject: [PATCH 2/2] Run migrate.py in the local quickstart; terminate the DO block's END The README quickstart loaded scripts/schema.sql and stopped, but that snapshot has no users.is_approved (nor lotto_photos), so login would fail on a database built that way. The quickstart now runs migrate.py and says why it is required. Also write the PL/pgSQL block's final END with a semicolon. PostgreSQL 16 accepted it without one, but the terminated form is the documented one. Verified on PostgreSQL 16: schema.sql + migrate.py (run twice), then register and login succeed and the new account is unapproved. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012k19dCKBK4J2UdDMJd5gLv --- README.md | 8 +++++++- scripts/migrate.py | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9759425..ca7f7a8 100644 --- a/README.md +++ b/README.md @@ -56,8 +56,14 @@ pip install -e . (both the SQLAlchemy ones and the raw-SQL ones), so it is the shortest path: ```bash psql -d safefamily < scripts/schema.sql +python scripts/migrate.py ``` -Regenerate it from a live database with `python scripts/db_export.py schema`. +`migrate.py` is required, not optional: it adds what is newer than the +`schema.sql` snapshot (for example `users.is_approved`, which every login reads, +and the `lotto_photos` table). It is safe to re-run, so run it after every +update too. + +Regenerate `schema.sql` from a live database with `python scripts/db_export.py schema`. If you would rather build it piecemeal: - SQLAlchemy models expect tables for users and notes. diff --git a/scripts/migrate.py b/scripts/migrate.py index 1977e5f..0a150ee 100644 --- a/scripts/migrate.py +++ b/scripts/migrate.py @@ -31,7 +31,7 @@ ELSE CREATE UNIQUE INDEX IF NOT EXISTS uq_users_username ON users (username); END IF; - END + END; $$ """, # Speeds up per-user history scans (week strip / activity heatmap on /todo)