The app had no cleanup of any kind: in multi-user mode every first visit mints a users row, so the demo has been accumulating one permanent account per visitor along with everything they generated. cleanup.py sweeps guests idle for AIDND_GUEST_RETENTION_DAYS (default 5), once at startup and then every few hours. Startup is the load-bearing trigger — the free tier sleeps after ~15 minutes, so a long timer rarely gets to fire. Idle is COALESCE(last_seen_at, created_at), not last_seen_at: _touch only writes that column hourly, and a guest minted by /auth/me has it NULL until its second request, so the simpler query would have deleted brand-new visitors mid-session. It's one Core DELETE rather than db.delete(user), which would SELECT every adventure, action and memory into Python purely to delete them — the same egress pattern as the 189x fix. Every FK from users down is ON DELETE CASCADE, so the database does the whole graph and returns a count. The filter requires is_guest AND email IS NULL, so registered users (who upgrade in place) and local mode's implicit user are both out of reach, and is_public is output-only so a guest can never own content another user can see. Session cookies have no expiry and can outlive a swept row; that path 401s and the frontend's existing retry re-mints a session. Guests are told: /auth/me serves guest_retention_days and the signup modal states the window, sourced from the server so it can't drift from what is enforced. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015CYEJKobJ2Re4Dv7qUoSA7
134 lines
5.0 KiB
Python
134 lines
5.0 KiB
Python
import re
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Request, Response
|
|
from sqlalchemy.orm import Session
|
|
|
|
from .. import auth, cleanup, limits, models, schemas, security
|
|
from ..database import get_db
|
|
from .settings import get_settings
|
|
|
|
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
|
|
|
EMAIL_RE = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
|
|
|
|
|
|
def _set_session_cookie(response: Response, user_id: int) -> None:
|
|
response.set_cookie(
|
|
auth.SESSION_COOKIE,
|
|
security.sign_session(user_id),
|
|
max_age=auth.COOKIE_MAX_AGE,
|
|
httponly=True,
|
|
samesite="lax",
|
|
secure=auth.COOKIE_SECURE,
|
|
path="/",
|
|
)
|
|
|
|
|
|
def me_payload(user: models.User, db: Session) -> dict:
|
|
settings = get_settings(db, user)
|
|
cfg = auth.resolve_provider_config(settings)
|
|
return {
|
|
"multi_user": auth.MULTI_USER,
|
|
"id": user.id,
|
|
"email": user.email,
|
|
"is_guest": user.is_guest,
|
|
# Trusted testers: unmetered demo turns, plus the AI Chat scratchpad.
|
|
"power_user": auth.is_power_user(user),
|
|
# How long an idle guest is kept before cleanup deletes it (None when
|
|
# the policy is off). Served rather than hardcoded in the UI so the
|
|
# number a guest is shown is the number actually enforced.
|
|
"guest_retention_days": cleanup.RETENTION_DAYS if cleanup.enabled() else None,
|
|
"demo": {
|
|
"enabled": auth.demo_enabled(),
|
|
"using_demo": cfg.using_demo,
|
|
"model": cfg.model if cfg.using_demo else None,
|
|
"turns_per_day": auth.DEMO_TURNS_PER_DAY,
|
|
"turns_left": auth.demo_turns_left(user) if auth.demo_enabled() else None,
|
|
"models": auth.DEMO_MODELS if auth.demo_enabled() else [],
|
|
},
|
|
}
|
|
|
|
|
|
@router.get("/me")
|
|
def me(request: Request, response: Response, db: Session = Depends(get_db)):
|
|
"""Who am I? In multi-user mode this also bootstraps the session: with no
|
|
(or an invalid) cookie it creates a guest user and sets one — the
|
|
frontend calls this on load and after any 401."""
|
|
if not auth.MULTI_USER:
|
|
user = auth.local_user(db)
|
|
else:
|
|
user = auth.resolve_session_user(request, db)
|
|
if user is None:
|
|
# Each new guest is a database row — cap how fast one IP can mint them.
|
|
limits.rate_limit("guest", request)
|
|
user = models.User(is_guest=True)
|
|
db.add(user)
|
|
db.commit()
|
|
_set_session_cookie(response, user.id)
|
|
return me_payload(user, db)
|
|
|
|
|
|
@router.post("/register")
|
|
def register(
|
|
payload: schemas.AuthCredentials,
|
|
request: Request,
|
|
db: Session = Depends(get_db),
|
|
user: models.User = Depends(auth.get_current_user),
|
|
):
|
|
"""Upgrade the current guest in place — same user_id, so every adventure,
|
|
scenario, script and setting they created as a guest is kept."""
|
|
if not auth.MULTI_USER:
|
|
raise HTTPException(400, "Accounts are disabled in local mode.")
|
|
limits.rate_limit("auth", request)
|
|
email = payload.email.strip().lower()
|
|
if not EMAIL_RE.match(email):
|
|
raise HTTPException(422, "Enter a valid email address.")
|
|
if len(payload.password) < 8:
|
|
raise HTTPException(422, "Password must be at least 8 characters.")
|
|
if not user.is_guest:
|
|
raise HTTPException(400, "This session is already registered.")
|
|
if db.query(models.User).filter(models.User.email == email).first():
|
|
raise HTTPException(409, "An account with this email already exists — log in instead.")
|
|
user.email = email
|
|
user.password_hash = security.hash_password(payload.password)
|
|
user.is_guest = False
|
|
db.commit()
|
|
return me_payload(user, db)
|
|
|
|
|
|
@router.post("/login")
|
|
def login(
|
|
payload: schemas.AuthCredentials,
|
|
request: Request,
|
|
response: Response,
|
|
db: Session = Depends(get_db),
|
|
):
|
|
"""Point this browser's session at an existing account. Any current guest
|
|
session is simply abandoned (its data stays under the guest user)."""
|
|
if not auth.MULTI_USER:
|
|
raise HTTPException(400, "Accounts are disabled in local mode.")
|
|
limits.rate_limit("auth", request)
|
|
email = payload.email.strip().lower()
|
|
# Per-account throttle: stops distributed guessing against one email even
|
|
# when the per-IP limit above is diluted across many source addresses.
|
|
limits.check_login_allowed(email)
|
|
user = db.query(models.User).filter(models.User.email == email).first()
|
|
if (
|
|
user is None
|
|
or not user.password_hash
|
|
or not security.verify_password(payload.password, user.password_hash)
|
|
):
|
|
limits.note_login_failure(email)
|
|
raise HTTPException(401, "Incorrect email or password.")
|
|
limits.note_login_success(email)
|
|
_set_session_cookie(response, user.id)
|
|
return me_payload(user, db)
|
|
|
|
|
|
@router.post("/logout")
|
|
def logout(response: Response):
|
|
if not auth.MULTI_USER:
|
|
raise HTTPException(400, "Accounts are disabled in local mode.")
|
|
response.delete_cookie(auth.SESSION_COOKIE, path="/")
|
|
return {"ok": True}
|