From 3c897812c894e0cc2ddde3332b3a6e4d7bf5d56e Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 1/9] fix(rate-limit): harden client IP extraction, auth limits, and read fast-path --- backend/core/rate_limit.py | 127 +++++++++++++++++++++++++--- backend/services/auth_rate_limit.py | 44 ++++++++-- 2 files changed, 151 insertions(+), 20 deletions(-) diff --git a/backend/core/rate_limit.py b/backend/core/rate_limit.py index 70e1a7d..59fed6e 100644 --- a/backend/core/rate_limit.py +++ b/backend/core/rate_limit.py @@ -1,12 +1,13 @@ from __future__ import annotations +import hashlib +import ipaddress +import math import os -import time import threading -import math -import hashlib +import time from collections import deque -from typing import Tuple, Dict, Optional, Union +from typing import Callable, Dict, Optional, Tuple, Union from core.database import get_db, lock_transaction_key from starlette.middleware.base import BaseHTTPMiddleware from starlette.concurrency import run_in_threadpool @@ -15,6 +16,75 @@ from core.settings import load_rate_limit_enabled +def _load_trusted_proxy_networks() -> tuple[ipaddress._BaseNetwork, ...]: + raw_cidrs = os.environ.get("FABLE_TRUSTED_PROXY_CIDRS", "").strip() + if not raw_cidrs: + return () + networks: list[ipaddress._BaseNetwork] = [] + for raw_cidr in raw_cidrs.split(","): + candidate = raw_cidr.strip() + if not candidate: + continue + try: + networks.append(ipaddress.ip_network(candidate, strict=False)) + except ValueError: + continue + return tuple(networks) + + +def _parse_ip(raw_ip: Optional[str]) -> Optional[ipaddress._BaseAddress]: + if not raw_ip: + return None + candidate = raw_ip.strip() + if not candidate: + return None + # Strip optional port on IPv4 like "203.0.113.1:1234" or bracketed IPv6 "[::1]:1234" + if candidate.startswith("[") and "]" in candidate: + candidate = candidate[1:candidate.index("]")] + elif candidate.count(":") == 1 and "." in candidate: + candidate = candidate.split(":", 1)[0] + try: + return ipaddress.ip_address(candidate) + except ValueError: + return None + + +def _is_trusted_proxy(raw_ip: Optional[str], networks: tuple[ipaddress._BaseNetwork, ...]) -> bool: + if not networks: + return False + parsed = _parse_ip(raw_ip) + if parsed is None: + return False + return any(parsed in network for network in networks) + + +def extract_client_ip(request: Request) -> str: + """Resolve the client IP, honoring forwarded headers only from trusted proxy CIDRs.""" + peer_host = request.client.host if request.client and request.client.host else "" + trusted_networks = _load_trusted_proxy_networks() + + if trusted_networks and _is_trusted_proxy(peer_host, trusted_networks): + forwarded_for = request.headers.get("x-forwarded-for", "") + if forwarded_for: + hops = [part.strip() for part in forwarded_for.split(",") if part.strip()] + for hop in reversed(hops): + parsed = _parse_ip(hop) + if parsed is None: + break + if not any(parsed in network for network in trusted_networks): + return str(parsed) + if hops: + parsed_first = _parse_ip(hops[0]) + if parsed_first is not None: + return str(parsed_first) + + real_ip = _parse_ip(request.headers.get("x-real-ip")) + if real_ip is not None: + return str(real_ip) + + return peer_host or "127.0.0.1" + + class SlidingWindowRateLimiter: """ Thread-safe in-memory sliding window rate limiter. @@ -110,6 +180,10 @@ def __init__( self._max_client_buckets = max_client_buckets self._last_capacity_cleanup = 0.0 self._cleanup_lock = threading.Lock() + self._reset_hooks: list[Callable[[], None]] = [] + + def add_reset_hook(self, hook: Callable[[], None]) -> None: + self._reset_hooks.append(hook) def is_allowed(self, client_id: str, tier: str = "general") -> Tuple[bool, int]: limit, window = self.limits.get(tier, self.limits["general"]) @@ -196,6 +270,8 @@ def reset(self) -> None: self._last_capacity_cleanup = 0.0 finally: connection.close() + for hook in self._reset_hooks: + hook() # Shared singleton instance configured via environment variables @@ -210,16 +286,37 @@ def reset(self) -> None: class RateLimitMiddleware(BaseHTTPMiddleware): """ - FastAPI / Starlette middleware enforcing sliding-window rate limiting. + FastAPI / Starlette middleware enforcing rate limiting. + Uses an in-memory sliding-window fast path for safe read-only requests (GET/HEAD/OPTIONS) + and the shared database token-bucket limiter for mutating requests. Rejects throttled requests with HTTP 429 and standard Retry-After header. """ + READ_ONLY_METHODS = frozenset({"GET", "HEAD", "OPTIONS"}) + def __init__( self, app, rate_limiter: Optional[Union[SlidingWindowRateLimiter, SharedTokenBucketRateLimiter]] = None, + read_rate_limiter: Optional[SlidingWindowRateLimiter] = None, ): super().__init__(app) self.rate_limiter = rate_limiter or limiter + if read_rate_limiter is not None: + self.read_rate_limiter = read_rate_limiter + elif isinstance(self.rate_limiter, SlidingWindowRateLimiter): + self.read_rate_limiter = self.rate_limiter + else: + auth_limit, auth_window = self.rate_limiter.limits.get("auth", (10, 60)) + general_limit, general_window = self.rate_limiter.limits.get("general", (60, 60)) + self.read_rate_limiter = SlidingWindowRateLimiter( + auth_limit=auth_limit, + auth_window=auth_window, + general_limit=general_limit, + general_window=general_window, + max_client_buckets=getattr(self.rate_limiter, "_max_client_buckets", 10_000), + ) + if isinstance(self.rate_limiter, SharedTokenBucketRateLimiter): + self.rate_limiter.add_reset_hook(self.read_rate_limiter.reset) self.exempt_paths = { "/api/v1/health", "/docs", @@ -236,19 +333,23 @@ async def dispatch(self, request: Request, call_next): if path in self.exempt_paths: return await call_next(request) - # Uvicorn rewrites request.client only for peers trusted by FORWARDED_ALLOW_IPS. - # Never use X-Forwarded-For directly because clients can supply it themselves. - client_ip = request.client.host if request.client and request.client.host else "127.0.0.1" + client_ip = extract_client_ip(request) # Credential checks and durable ingestion writes use the stricter tier. sensitive_path = path.startswith(("/api/v1/auth", "/api/v1/stories/ingest")) tier = "auth" if sensitive_path else "general" - allowed, retry_after = await run_in_threadpool( - self.rate_limiter.is_allowed, - client_ip, - tier, - ) + is_read_only = request.method.upper() in self.READ_ONLY_METHODS + if is_read_only: + if hasattr(self.rate_limiter, "limits"): + self.read_rate_limiter.limits = dict(self.rate_limiter.limits) + allowed, retry_after = self.read_rate_limiter.is_allowed(client_ip, tier) + else: + allowed, retry_after = await run_in_threadpool( + self.rate_limiter.is_allowed, + client_ip, + tier, + ) if not allowed: return JSONResponse( status_code=429, diff --git a/backend/services/auth_rate_limit.py b/backend/services/auth_rate_limit.py index f6ea5c6..4b8e997 100644 --- a/backend/services/auth_rate_limit.py +++ b/backend/services/auth_rate_limit.py @@ -23,6 +23,11 @@ def _positive_int(name: str, default: int) -> int: LOGIN_LIMIT_PER_ACCOUNT_IP = _positive_int("FABLE_AUTH_LOGIN_LIMIT_PER_ACCOUNT_IP", 10) PASSWORD_RESET_LIMIT_PER_IP = _positive_int("FABLE_AUTH_PASSWORD_RESET_LIMIT_PER_IP", 10) PASSWORD_RESET_LIMIT_PER_ACCOUNT_IP = _positive_int("FABLE_AUTH_PASSWORD_RESET_LIMIT_PER_ACCOUNT_IP", 5) +PASSWORD_RESET_CONFIRM_LIMIT_PER_IP = _positive_int("FABLE_AUTH_PASSWORD_RESET_CONFIRM_LIMIT_PER_IP", 5) +PASSWORD_RESET_CONFIRM_LIMIT_PER_ACCOUNT_IP = _positive_int( + "FABLE_AUTH_PASSWORD_RESET_CONFIRM_LIMIT_PER_ACCOUNT_IP", 5 +) +MAX_AUTH_RATE_LIMIT_BUCKETS = _positive_int("FABLE_AUTH_RATE_LIMIT_MAX_BUCKETS", 10_000) def _bucket_key(action: str, dimension: str, value: str) -> str: @@ -30,19 +35,42 @@ def _bucket_key(action: str, dimension: str, value: str) -> str: return f"{action}:{dimension}:{digest}" +def _evict_auth_rate_limit_overflow(connection) -> None: + lock_transaction_key(connection, "auth_rate_limits:capacity") + bucket_count = int( + connection.execute("SELECT COUNT(*) AS bucket_count FROM auth_rate_limits").fetchone()["bucket_count"] + ) + if bucket_count >= MAX_AUTH_RATE_LIMIT_BUCKETS: + overflow = bucket_count - MAX_AUTH_RATE_LIMIT_BUCKETS + 1 + connection.execute( + """ + DELETE FROM auth_rate_limits + WHERE bucket_key IN ( + SELECT bucket_key FROM auth_rate_limits + ORDER BY window_expires_at ASC, bucket_key ASC + LIMIT ? + ) + """, + (overflow,), + ) + + def enforce_auth_rate_limit(action: str, client_host: str, identity: Optional[str] = None) -> None: now = int(time.time()) if action == "register": buckets = [ (_bucket_key(action, "ip", client_host), REGISTER_LIMIT_PER_IP), ] - elif action in {"login", "password_reset"}: - ip_limit = LOGIN_LIMIT_PER_IP if action == "login" else PASSWORD_RESET_LIMIT_PER_IP - account_limit = ( - LOGIN_LIMIT_PER_ACCOUNT_IP - if action == "login" - else PASSWORD_RESET_LIMIT_PER_ACCOUNT_IP - ) + elif action in {"login", "password_reset", "password_reset_confirm"}: + if action == "login": + ip_limit = LOGIN_LIMIT_PER_IP + account_limit = LOGIN_LIMIT_PER_ACCOUNT_IP + elif action == "password_reset": + ip_limit = PASSWORD_RESET_LIMIT_PER_IP + account_limit = PASSWORD_RESET_LIMIT_PER_ACCOUNT_IP + else: + ip_limit = PASSWORD_RESET_CONFIRM_LIMIT_PER_IP + account_limit = PASSWORD_RESET_CONFIRM_LIMIT_PER_ACCOUNT_IP buckets = [(_bucket_key(action, "ip", client_host), ip_limit)] if identity: buckets.append( @@ -71,6 +99,8 @@ def enforce_auth_rate_limit(action: str, client_host: str, identity: Optional[st (bucket_key,), ).fetchone() if row is None or row["window_expires_at"] <= now: + if row is None: + _evict_auth_rate_limit_overflow(connection) connection.execute( """INSERT INTO auth_rate_limits (bucket_key, window_expires_at, request_count) From a82b27b7263b025a1a75356f2b7568e823644d49 Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 2/9] feat(backend): enforce unique handles, optimize story queries, and add lifecycle endpoints --- backend/api/v1/endpoints/auth.py | 24 +++- backend/api/v1/endpoints/stories.py | 22 +++- backend/core/database.py | 31 +++++ backend/schemas.py | 2 + backend/schemas/__init__.py | 2 + backend/schemas/schemas.py | 15 +++ backend/services/auth_service.py | 114 ++++++++++++++++++- backend/services/gutenberg.py | 20 +++- backend/services/story_service.py | 169 ++++++++++++++++++++++++---- 9 files changed, 363 insertions(+), 36 deletions(-) diff --git a/backend/api/v1/endpoints/auth.py b/backend/api/v1/endpoints/auth.py index 474d99f..c558ec9 100644 --- a/backend/api/v1/endpoints/auth.py +++ b/backend/api/v1/endpoints/auth.py @@ -1,4 +1,5 @@ -from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request, status +from fastapi import APIRouter, BackgroundTasks, Header, HTTPException, Request, Response, status +from core.rate_limit import extract_client_ip from schemas import ( RegisterRequest, LoginRequest, @@ -23,13 +24,13 @@ @router.post("/auth/register", response_model=AuthResponse, status_code=status.HTTP_201_CREATED) def register(req: RegisterRequest, request: Request): - client_host = request.client.host if request.client else "unknown" + client_host = extract_client_ip(request) enforce_auth_rate_limit("register", client_host) return auth_service.register_user(req) @router.post("/auth/login", response_model=AuthResponse) def login(req: LoginRequest, request: Request): - client_host = request.client.host if request.client else "unknown" + client_host = extract_client_ip(request) enforce_auth_rate_limit("login", client_host, req.email) return auth_service.login_user(req) @@ -48,7 +49,7 @@ def request_password_reset( detail="Password recovery is temporarily unavailable.", ) from error - client_host = request.client.host if request.client else "unknown" + client_host = extract_client_ip(request) enforce_auth_rate_limit("password_reset", client_host, payload.email) token = auth_service.issue_password_reset_token(payload.email) if token is not None: @@ -64,8 +65,11 @@ def request_password_reset( @router.post("/auth/password-reset/confirm", status_code=status.HTTP_204_NO_CONTENT) -def confirm_password_reset(payload: PasswordResetConfirmRequest): +def confirm_password_reset(payload: PasswordResetConfirmRequest, request: Request): + client_host = extract_client_ip(request) + enforce_auth_rate_limit("password_reset_confirm", client_host, payload.token[:16]) auth_service.reset_password_with_token(payload.token, payload.new_password) + return Response(status_code=status.HTTP_204_NO_CONTENT) @router.get("/auth/me", response_model=UserDTO) def get_me(authorization: str = Header(None)): @@ -82,10 +86,18 @@ def get_my_stories(authorization: str = Header(None)): @router.patch("/auth/me", response_model=UserDTO) def update_me(req: ProfileUpdateRequest, authorization: str = Header(None)): auth_service.get_current_user_from_header(authorization) - token = authorization.split(" ", 1)[1] + token = authorization.split(" ", 1)[1].strip() return auth_service.update_current_user(token, req) +@router.delete("/auth/me", status_code=status.HTTP_204_NO_CONTENT) +def delete_me(authorization: str = Header(None)): + auth_service.get_current_user_from_header(authorization) + token = authorization.split(" ", 1)[1].strip() + auth_service.delete_current_user(token) + return Response(status_code=status.HTTP_204_NO_CONTENT) + + @router.post("/auth/me/reading-sessions", status_code=status.HTTP_204_NO_CONTENT) def record_reading_session( request: ReadingSessionRequest, diff --git a/backend/api/v1/endpoints/stories.py b/backend/api/v1/endpoints/stories.py index 24cb07f..9b9e43d 100644 --- a/backend/api/v1/endpoints/stories.py +++ b/backend/api/v1/endpoints/stories.py @@ -1,7 +1,7 @@ from datetime import datetime from typing import Optional from uuid import UUID -from fastapi import APIRouter, Header, Query, status +from fastapi import APIRouter, Header, Query, Response, status from schemas import ( StoryDTO, @@ -9,7 +9,8 @@ GenreDTO, WriterDTO, UpdateFeedDTO, - CreateStoryRequest + CreateStoryRequest, + UpdateStoryRequest, ) from services import auth_service, story_service @@ -59,3 +60,20 @@ def get_story_chapter_by_number(story_id: UUID, chapter_number: int): def create_story(payload: CreateStoryRequest, authorization: str = Header(None)): user = auth_service.get_current_user_from_header(authorization) return story_service.create_story(payload, author=user.name, owner_user_id=user.id) + + +@router.patch("/stories/{story_id}", response_model=StoryDTO) +def update_story( + story_id: UUID, + payload: UpdateStoryRequest, + authorization: str = Header(None), +): + user = auth_service.get_current_user_from_header(authorization) + return story_service.update_story(story_id, payload, owner_user_id=user.id) + + +@router.delete("/stories/{story_id}", status_code=status.HTTP_204_NO_CONTENT) +def delete_story(story_id: UUID, authorization: str = Header(None)): + user = auth_service.get_current_user_from_header(authorization) + story_service.delete_story(story_id, owner_user_id=user.id) + return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/backend/core/database.py b/backend/core/database.py index 8160058..d1919fc 100644 --- a/backend/core/database.py +++ b/backend/core/database.py @@ -308,6 +308,8 @@ def init_db(): """) conn.execute("CREATE INDEX IF NOT EXISTS idx_account_shelf_owner_device ON account_shelf_items (owner_user_id, device_id);") conn.execute("CREATE INDEX IF NOT EXISTS idx_account_shelf_story ON account_shelf_items (story_id);") + conn.execute("CREATE INDEX IF NOT EXISTS idx_stories_owner_created ON stories (owner_user_id, created_at_utc DESC);") + conn.execute("CREATE INDEX IF NOT EXISTS idx_shelf_story_owner ON account_shelf_items (story_id, owner_user_id);") conn.execute(""" CREATE TABLE IF NOT EXISTS reading_sessions ( owner_user_id TEXT NOT NULL, @@ -337,6 +339,35 @@ def init_db(): _add_column_if_missing(conn, "users", "handle", "TEXT NOT NULL DEFAULT ''") _add_column_if_missing(conn, "users", "bio", "TEXT NOT NULL DEFAULT ''") conn.execute("CREATE INDEX IF NOT EXISTS idx_users_email ON users (email);") + duplicate_handles = conn.execute( + """ + SELECT LOWER(handle) AS lowered_handle + FROM users + WHERE handle <> '' + GROUP BY LOWER(handle) + HAVING COUNT(*) > 1 + """ + ).fetchall() + for duplicate in duplicate_handles: + rows = conn.execute( + """ + SELECT id, handle + FROM users + WHERE LOWER(handle) = ? + ORDER BY created_at_utc ASC, id ASC + """, + (duplicate["lowered_handle"],), + ).fetchall() + for row in rows[1:]: + suffix = row["id"].replace("-", "")[:6] + base = row["handle"][:33] + conn.execute( + "UPDATE users SET handle = ? WHERE id = ?", + (f"{base}_{suffix}", row["id"]), + ) + conn.execute( + "CREATE UNIQUE INDEX IF NOT EXISTS idx_users_handle_lower ON users (LOWER(handle)) WHERE handle <> '';" + ) conn.execute(""" CREATE TABLE IF NOT EXISTS user_sessions ( token_hash TEXT PRIMARY KEY, diff --git a/backend/schemas.py b/backend/schemas.py index 394fbb6..e77ab30 100644 --- a/backend/schemas.py +++ b/backend/schemas.py @@ -8,6 +8,7 @@ WriterDTO, UpdateFeedDTO, CreateStoryRequest, + UpdateStoryRequest, ShelfSyncItemDTO, ShelfSyncPayload, ShelfSyncResponse, @@ -23,6 +24,7 @@ "WriterDTO", "UpdateFeedDTO", "CreateStoryRequest", + "UpdateStoryRequest", "ShelfSyncItemDTO", "ShelfSyncPayload", "ShelfSyncResponse", diff --git a/backend/schemas/__init__.py b/backend/schemas/__init__.py index 4d28ca4..5d1a72a 100644 --- a/backend/schemas/__init__.py +++ b/backend/schemas/__init__.py @@ -5,6 +5,7 @@ WriterDTO, UpdateFeedDTO, CreateStoryRequest, + UpdateStoryRequest, ShelfSyncItemDTO, ShelfSyncPayload, ShelfSyncResponse, @@ -27,6 +28,7 @@ "WriterDTO", "UpdateFeedDTO", "CreateStoryRequest", + "UpdateStoryRequest", "ShelfSyncItemDTO", "ShelfSyncPayload", "ShelfSyncResponse", diff --git a/backend/schemas/schemas.py b/backend/schemas/schemas.py index 8e9e71b..d2d56fb 100644 --- a/backend/schemas/schemas.py +++ b/backend/schemas/schemas.py @@ -50,6 +50,7 @@ class StoryDTO(BaseModel): source_provider: str = Field(default="FABLE_ORIGINAL", serialization_alias="sourceProvider") provider_id: Optional[str] = Field(default=None, serialization_alias="providerId") provider_download_count: Optional[int] = Field(default=None, serialization_alias="providerDownloadCount") + owner_user_id: Optional[UUID] = Field(default=None, serialization_alias="ownerUserId") chapters: Optional[list[ChapterDTO]] = None model_config = { @@ -106,6 +107,20 @@ class CreateStoryRequest(BaseModel): "extra": "forbid", } + +class UpdateStoryRequest(BaseModel): + title: Optional[str] = Field(default=None, min_length=1, max_length=120) + genre: Optional[str] = Field(default=None, min_length=1, max_length=50) + chapter: Optional[str] = Field(default=None, max_length=120) + synopsis: Optional[str] = Field(default=None, max_length=2_000) + content: Optional[str] = Field(default=None, max_length=50_000) + read_time_minutes: Optional[int] = Field(default=None, ge=0, alias="readTimeMinutes") + + model_config = { + "populate_by_name": True, + "extra": "forbid", + } + class ShelfSyncItemDTO(BaseModel): story_id: UUID = Field(..., alias="storyId", serialization_alias="storyId") reading_progress: float = Field(..., ge=0.0, le=1.0, alias="readingProgress", serialization_alias="readingProgress") diff --git a/backend/services/auth_service.py b/backend/services/auth_service.py index 9b4017a..e901915 100644 --- a/backend/services/auth_service.py +++ b/backend/services/auth_service.py @@ -47,6 +47,50 @@ def _normalized_handle(value: str) -> str: return "" return handle if handle.startswith("@") else f"@{handle}" + +RESERVED_AUTHOR_NAMES = frozenset({ + "aesop", + "jane austen", + "mary shelley", + "herman melville", + "bram stoker", + "lewis carroll", + "brothers grimm", + "arthur conan doyle", + "h. g. wells", + "h.g. wells", + "h g wells", + "hg wells", + "edgar allan poe", + "washington irving", + "franz kafka", + "oscar wilde", + "robert louis stevenson", + "homer", + "sun tzu", + "charles dickens", + "mark twain", + "william shakespeare", +}) + + +def _normalized_identity_token(value: str) -> str: + cleaned = value.strip().lstrip("@").casefold() + return " ".join(cleaned.split()) + + +def _validate_public_identity(name: str, handle: str) -> None: + if _normalized_identity_token(name) in RESERVED_AUTHOR_NAMES: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="That author name is reserved for catalog works.", + ) + if handle and _normalized_identity_token(handle) in RESERVED_AUTHOR_NAMES: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="That handle is reserved for catalog works.", + ) + def hash_password(password: str) -> str: """Hash passwords with a versioned PBKDF2-HMAC-SHA256 format.""" salt = secrets.token_bytes(16) @@ -130,6 +174,10 @@ def _issue_session(user_id: str) -> str: def register_user(req: RegisterRequest) -> AuthResponse: """Register a new user account with validated credentials and return authentication token.""" normalized_email = req.email.strip().lower() + clean_name = req.name.strip() + normalized_handle = _normalized_handle(req.handle) + _validate_public_identity(clean_name, normalized_handle) + conn = get_db() try: with conn: @@ -139,6 +187,16 @@ def register_user(req: RegisterRequest) -> AuthResponse: status_code=status.HTTP_409_CONFLICT, detail="Email is already registered" ) + if normalized_handle: + existing_handle = conn.execute( + "SELECT id FROM users WHERE LOWER(handle) = LOWER(?)", + (normalized_handle,), + ).fetchone() + if existing_handle: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Handle is already taken" + ) user_id = str(uuid4()) now = datetime.now(timezone.utc).isoformat() @@ -146,7 +204,7 @@ def register_user(req: RegisterRequest) -> AuthResponse: conn.execute(""" INSERT INTO users (id, email, password_hash, name, handle, bio, avatar_image_name, created_at_utc, updated_at_utc) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) - """, (user_id, normalized_email, pwd_hash, req.name.strip(), _normalized_handle(req.handle), "", None, now, now)) + """, (user_id, normalized_email, pwd_hash, clean_name, normalized_handle, "", None, now, now)) finally: conn.close() @@ -251,17 +309,35 @@ def revoke_session(token: str) -> None: def update_current_user(token: str, req: ProfileUpdateRequest) -> UserDTO: user_id = str(get_current_user(token).id) + clean_name = req.name.strip() + normalized_handle = _normalized_handle(req.handle) + _validate_public_identity(clean_name, normalized_handle) now = datetime.now(timezone.utc).isoformat() conn = get_db() try: with conn: + if normalized_handle: + existing_handle = conn.execute( + "SELECT id FROM users WHERE LOWER(handle) = LOWER(?) AND id != ?", + (normalized_handle, user_id), + ).fetchone() + if existing_handle: + raise HTTPException( + status_code=status.HTTP_409_CONFLICT, + detail="Handle is already taken", + ) + result = conn.execute( """UPDATE users SET name = ?, handle = ?, bio = ?, updated_at_utc = ? WHERE id = ?""", - (req.name.strip(), _normalized_handle(req.handle), req.bio.strip(), now, user_id) + (clean_name, normalized_handle, req.bio.strip(), now, user_id) ) if result.rowcount != 1: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found") + conn.execute( + "UPDATE stories SET author = ?, updated_at_utc = ? WHERE owner_user_id = ?", + (clean_name, now, user_id), + ) row = conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone() finally: conn.close() @@ -269,6 +345,40 @@ def update_current_user(token: str, req: ProfileUpdateRequest) -> UserDTO: return _to_user_dto(row) +def delete_current_user(token: str) -> None: + user = get_current_user(token) + user_id = str(user.id) + conn = get_db() + try: + conn.execute("BEGIN IMMEDIATE") + conn.execute("DELETE FROM user_sessions WHERE user_id = ?", (user_id,)) + conn.execute("DELETE FROM password_reset_tokens WHERE user_id = ?", (user_id,)) + conn.execute("DELETE FROM account_shelf_items WHERE owner_user_id = ?", (user_id,)) + conn.execute("DELETE FROM reading_sessions WHERE owner_user_id = ?", (user_id,)) + conn.execute( + "DELETE FROM shelf_items WHERE story_id IN (SELECT id FROM stories WHERE owner_user_id = ?)", + (user_id,), + ) + conn.execute( + "DELETE FROM account_shelf_items WHERE story_id IN (SELECT id FROM stories WHERE owner_user_id = ?)", + (user_id,), + ) + conn.execute( + "DELETE FROM reading_sessions WHERE story_id IN (SELECT id FROM stories WHERE owner_user_id = ?)", + (user_id,), + ) + conn.execute("DELETE FROM chapters WHERE story_id IN (SELECT id FROM stories WHERE owner_user_id = ?)", (user_id,)) + conn.execute("DELETE FROM stories WHERE owner_user_id = ?", (user_id,)) + conn.execute("DELETE FROM users WHERE id = ?", (user_id,)) + conn.commit() + except Exception: + if conn.in_transaction: + conn.rollback() + raise + finally: + conn.close() + + def issue_password_reset_token(email: str) -> Optional[str]: normalized_email = email.strip().lower() conn = get_db() diff --git a/backend/services/gutenberg.py b/backend/services/gutenberg.py index 73776fe..7dffcee 100644 --- a/backend/services/gutenberg.py +++ b/backend/services/gutenberg.py @@ -46,6 +46,8 @@ _GUTENBERG_CATALOG_CACHE: Optional[Tuple[float, List["GutenbergCatalogEntry"]]] = None _GUTENBERG_CATALOG_STALE_CACHE: Optional[Tuple[float, List["GutenbergCatalogEntry"]]] = None _GUTENBERG_CATALOG_LAST_REFRESH_ATTEMPT = 0.0 +GUTENBERG_AUTHORS_CACHE_TTL_SECONDS = 3600.0 +_GUTENBERG_AUTHORS_CACHE: Optional[Tuple[float, List["GutenbergCatalogEntry"], List[WriterDTO]]] = None _RDF_NAMESPACES = { "dc": "http://purl.org/dc/terms/", @@ -415,11 +417,23 @@ async def _fetch_gutenberg_book_metadata(client: httpx.AsyncClient, gutenberg_id return next((item for item in books if item.get("id") == gutenberg_id), None) +def invalidate_gutenberg_authors_cache() -> None: + global _GUTENBERG_AUTHORS_CACHE + _GUTENBERG_AUTHORS_CACHE = None + + async def get_gutenberg_authors(limit: int = 6) -> list[WriterDTO]: """Return authors and book counts from the live Project Gutenberg catalog.""" + global _GUTENBERG_AUTHORS_CACHE async with httpx.AsyncClient(timeout=15.0, follow_redirects=True) as client: entries = await _load_gutenberg_catalog(client) + now = time.monotonic() + if _GUTENBERG_AUTHORS_CACHE is not None: + cached_at, cached_entries, cached_writers = _GUTENBERG_AUTHORS_CACHE + if entries is cached_entries and now - cached_at < GUTENBERG_AUTHORS_CACHE_TTL_SECONDS: + return cached_writers[:max(0, limit)] + authors: dict[str, tuple[str, int]] = {} for entry in entries: for raw_author in entry.authors.split(";"): @@ -431,7 +445,7 @@ async def get_gutenberg_authors(limit: int = 6) -> list[WriterDTO]: authors[key] = (display_name, count + 1) ranked_authors = sorted(authors.values(), key=lambda author: (-author[1], author[0].casefold())) - return [ + writers = [ WriterDTO( id=uuid5(GUTENBERG_AUTHOR_NAMESPACE, name.casefold()), name=name, @@ -440,8 +454,10 @@ async def get_gutenberg_authors(limit: int = 6) -> list[WriterDTO]: story_count=count, rating=None, ) - for name, count in ranked_authors[:max(0, limit)] + for name, count in ranked_authors ] + _GUTENBERG_AUTHORS_CACHE = (now, entries, writers) + return writers[:max(0, limit)] def _cached_gutenberg_chapters(gutenberg_id: int) -> Optional[list[ChapterDTO]]: diff --git a/backend/services/story_service.py b/backend/services/story_service.py index 461d593..dbcf98e 100644 --- a/backend/services/story_service.py +++ b/backend/services/story_service.py @@ -13,16 +13,33 @@ GenreDTO, StoryDTO, UpdateFeedDTO, + UpdateStoryRequest, WriterDTO, ) IDENTIFIER_NAMESPACE = UUID("b28f1a39-ff20-5d3c-9ff0-994df9324c22") -STORY_SUMMARY_COLUMNS = """id, title, author, genre, chapter, synopsis, '' AS content, - read_time_minutes, is_bookmarked, is_completed, created_at_utc, updated_at_utc, - cover_image_name, hero_image_name, cover_image_url, total_pages, current_page, - progress_percent, rating, saves_count, reads_count, is_tale_of_the_day, - is_recent_submission, is_curator_spotlight, badge_text, total_chapters, - content_format, source_provider, provider_id, provider_download_count, owner_user_id""" +STORY_SUMMARY_COLUMNS = """stories.id, stories.title, stories.author, stories.genre, stories.chapter, stories.synopsis, '' AS content, + stories.read_time_minutes, stories.is_bookmarked, stories.is_completed, stories.created_at_utc, stories.updated_at_utc, + stories.cover_image_name, stories.hero_image_name, stories.cover_image_url, stories.total_pages, stories.current_page, + stories.progress_percent, stories.rating, stories.saves_count, stories.reads_count, stories.is_tale_of_the_day, + stories.is_recent_submission, stories.is_curator_spotlight, stories.badge_text, stories.total_chapters, + stories.content_format, stories.source_provider, stories.provider_id, stories.provider_download_count, stories.owner_user_id""" +STORY_SHELF_COUNTS_JOIN = """ +LEFT JOIN ( + SELECT + story_id, + COUNT(DISTINCT CASE WHEN is_bookmarked = 1 THEN owner_user_id END) AS computed_saves_count, + COUNT(DISTINCT CASE WHEN reading_progress > 0 THEN owner_user_id END) AS computed_reads_count + FROM account_shelf_items + GROUP BY story_id +) rc ON rc.story_id = stories.id +""" + + +def invalidate_top_authors_cache() -> None: + from services import gutenberg + + gutenberg.invalidate_gutenberg_authors_cache() def _is_legacy_demo_image_url(value: str) -> bool: @@ -82,9 +99,13 @@ def row_to_story_dto( for chapter in chapter_rows ] + keys = row.keys() saves_count = 0 reads_count = 0 - if conn: + if "computed_saves_count" in keys and "computed_reads_count" in keys: + saves_count = int(row["computed_saves_count"] or 0) + reads_count = int(row["computed_reads_count"] or 0) + elif conn: shelf_counts = conn.execute( """ SELECT @@ -98,12 +119,13 @@ def row_to_story_dto( saves_count = shelf_counts["saves_count"] reads_count = shelf_counts["reads_count"] - keys = row.keys() provider_id = row["provider_id"] if "provider_id" in keys else None source_provider = row["source_provider"] if "source_provider" in keys else "FABLE_ORIGINAL" cover_url = row["cover_image_url"] if "cover_image_url" in keys else None if not provider_id or source_provider not in {"GUTENBERG", "MANGADEX", "STANDARD_EBOOKS"}: cover_url = None + raw_owner_id = row["owner_user_id"] if "owner_user_id" in keys else None + owner_user_id = UUID(raw_owner_id) if raw_owner_id else None return StoryDTO( id=story_id, title=row["title"], @@ -135,6 +157,7 @@ def row_to_story_dto( source_provider=source_provider or "FABLE_ORIGINAL", provider_id=provider_id, provider_download_count=row["provider_download_count"] if "provider_download_count" in keys else None, + owner_user_id=owner_user_id, chapters=chapters, ) @@ -148,19 +171,24 @@ def get_stories( ) -> list[StoryDTO]: conn = get_db() try: - query = f"SELECT {STORY_SUMMARY_COLUMNS} FROM stories WHERE 1=1" + query = ( + f"SELECT {STORY_SUMMARY_COLUMNS}, " + "COALESCE(rc.computed_saves_count, 0) AS computed_saves_count, " + "COALESCE(rc.computed_reads_count, 0) AS computed_reads_count " + f"FROM stories {STORY_SHELF_COUNTS_JOIN} WHERE 1=1" + ) params: list[object] = [] if genre and genre.lower() != "all": - query += " AND LOWER(genre) = LOWER(?)" + query += " AND LOWER(stories.genre) = LOWER(?)" params.append(genre) if search: - query += " AND (LOWER(title) LIKE ? OR LOWER(synopsis) LIKE ? OR LOWER(author) LIKE ?)" + query += " AND (LOWER(stories.title) LIKE ? OR LOWER(stories.synopsis) LIKE ? OR LOWER(stories.author) LIKE ?)" term = f"%{search.lower()}%" params.extend([term, term, term]) if since: - query += " AND updated_at_utc > ?" + query += " AND stories.updated_at_utc > ?" params.append(since.isoformat()) - query += " ORDER BY is_tale_of_the_day DESC, created_at_utc DESC, id ASC LIMIT ? OFFSET ?" + query += " ORDER BY stories.is_tale_of_the_day DESC, stories.created_at_utc DESC, stories.id ASC LIMIT ? OFFSET ?" params.extend((limit, offset)) rows = conn.execute(query, params).fetchall() return [row_to_story_dto(row, conn=conn) for row in rows] @@ -172,7 +200,10 @@ def get_story_by_id(story_id: UUID) -> StoryDTO: conn = get_db() try: row = conn.execute( - "SELECT * FROM stories WHERE id = ?", + "SELECT stories.*, " + "COALESCE(rc.computed_saves_count, 0) AS computed_saves_count, " + "COALESCE(rc.computed_reads_count, 0) AS computed_reads_count " + f"FROM stories {STORY_SHELF_COUNTS_JOIN} WHERE stories.id = ?", (str(story_id),), ).fetchone() if not row: @@ -297,6 +328,7 @@ def create_story(payload: CreateStoryRequest, author: str, owner_user_id: UUID) finally: conn.close() + invalidate_top_authors_cache() return StoryDTO( id=UUID(story_id), title=payload.title, @@ -314,17 +346,100 @@ def create_story(payload: CreateStoryRequest, author: str, owner_user_id: UUID) total_chapters=1, content_format=content_format, source_provider=source_provider, + owner_user_id=owner_user_id, rating=None, saves_count="0", reads_count="0", ) +def update_story(story_id: UUID, payload: UpdateStoryRequest, owner_user_id: UUID) -> StoryDTO: + now_iso = datetime.now(timezone.utc).isoformat() + conn = get_db() + try: + row = conn.execute("SELECT * FROM stories WHERE id = ?", (str(story_id),)).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Story not found") + if row["owner_user_id"] != str(owner_user_id): + raise HTTPException(status_code=403, detail="You do not have permission to modify this story") + + updates: dict[str, object] = {"updated_at_utc": now_iso} + if payload.title is not None: + updates["title"] = payload.title + if payload.genre is not None: + updates["genre"] = payload.genre + if payload.chapter is not None: + updates["chapter"] = payload.chapter + if payload.synopsis is not None: + updates["synopsis"] = payload.synopsis + if payload.content is not None: + updates["content"] = payload.content + if payload.read_time_minutes is not None: + updates["read_time_minutes"] = payload.read_time_minutes + + assignments = ", ".join(f"{column} = ?" for column in updates) + params = list(updates.values()) + [str(story_id), str(owner_user_id)] + with conn: + conn.execute( + f"UPDATE stories SET {assignments} WHERE id = ? AND owner_user_id = ?", + params, + ) + if payload.content is not None or payload.chapter is not None: + chapter_row = conn.execute( + "SELECT id, title, content FROM chapters WHERE story_id = ? AND chapter_number = 1", + (str(story_id),), + ).fetchone() + if chapter_row: + next_title = payload.chapter if payload.chapter is not None else chapter_row["title"] + next_content = payload.content if payload.content is not None else chapter_row["content"] + words = len(next_content.split()) if next_content else 0 + conn.execute( + "UPDATE chapters SET title = ?, content = ?, word_count = ? WHERE id = ?", + (next_title, next_content, words, chapter_row["id"]), + ) + finally: + conn.close() + + invalidate_top_authors_cache() + return get_story_by_id(story_id) + + +def delete_story(story_id: UUID, owner_user_id: UUID) -> None: + conn = get_db() + try: + row = conn.execute( + "SELECT id, owner_user_id FROM stories WHERE id = ?", + (str(story_id),), + ).fetchone() + if not row: + raise HTTPException(status_code=404, detail="Story not found") + if row["owner_user_id"] != str(owner_user_id): + raise HTTPException(status_code=403, detail="You do not have permission to delete this story") + + with conn: + conn.execute("DELETE FROM shelf_items WHERE story_id = ?", (str(story_id),)) + conn.execute("DELETE FROM account_shelf_items WHERE story_id = ?", (str(story_id),)) + conn.execute("DELETE FROM reading_sessions WHERE story_id = ?", (str(story_id),)) + conn.execute("DELETE FROM chapters WHERE story_id = ?", (str(story_id),)) + conn.execute( + "DELETE FROM stories WHERE id = ? AND owner_user_id = ?", + (str(story_id), str(owner_user_id)), + ) + finally: + conn.close() + + invalidate_top_authors_cache() + + def get_user_stories(owner_user_id: UUID) -> list[StoryDTO]: conn = get_db() try: rows = conn.execute( - f"SELECT {STORY_SUMMARY_COLUMNS} FROM stories WHERE owner_user_id = ? ORDER BY created_at_utc DESC", + f"SELECT {STORY_SUMMARY_COLUMNS}, " + "COALESCE(rc.computed_saves_count, 0) AS computed_saves_count, " + "COALESCE(rc.computed_reads_count, 0) AS computed_reads_count " + f"FROM stories {STORY_SHELF_COUNTS_JOIN} " + "WHERE stories.owner_user_id = ? ORDER BY stories.created_at_utc DESC", (str(owner_user_id),), ).fetchall() return [row_to_story_dto(row, conn=conn) for row in rows] @@ -379,25 +494,31 @@ async def get_top_authors() -> list[WriterDTO]: def get_update_feed() -> UpdateFeedDTO: conn = get_db() try: + base_select = ( + f"SELECT {STORY_SUMMARY_COLUMNS}, " + "COALESCE(rc.computed_saves_count, 0) AS computed_saves_count, " + "COALESCE(rc.computed_reads_count, 0) AS computed_reads_count " + f"FROM stories {STORY_SHELF_COUNTS_JOIN}" + ) totd_row = conn.execute( f""" - SELECT {STORY_SUMMARY_COLUMNS} FROM stories - WHERE is_tale_of_the_day = 1 - ORDER BY created_at_utc DESC LIMIT 1 + {base_select} + WHERE stories.is_tale_of_the_day = 1 + ORDER BY stories.created_at_utc DESC LIMIT 1 """ ).fetchone() curator_row = conn.execute( f""" - SELECT {STORY_SUMMARY_COLUMNS} FROM stories - WHERE is_curator_spotlight = 1 - ORDER BY created_at_utc DESC LIMIT 1 + {base_select} + WHERE stories.is_curator_spotlight = 1 + ORDER BY stories.created_at_utc DESC LIMIT 1 """ ).fetchone() recent_rows = conn.execute( f""" - SELECT {STORY_SUMMARY_COLUMNS} FROM stories - WHERE is_recent_submission = 1 - ORDER BY created_at_utc DESC LIMIT 10 + {base_select} + WHERE stories.is_recent_submission = 1 + ORDER BY stories.created_at_utc DESC LIMIT 10 """ ).fetchall() total_count = conn.execute( From 384a01cb184ab17436deb872f817c23275210a5c Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 3/9] test(backend): cover Plan 06 security, caching, and lifecycle flows --- backend/test_main.py | 327 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 327 insertions(+) diff --git a/backend/test_main.py b/backend/test_main.py index 9b925ac..75f7a9d 100644 --- a/backend/test_main.py +++ b/backend/test_main.py @@ -2612,3 +2612,330 @@ def test_security_headers_and_sqlite_foreign_keys_enforced(): assert journal_mode.lower() == "wal" finally: conn.close() + + +def test_password_reset_confirm_is_rate_limited_and_bounds_buckets(monkeypatch): + from core.database import get_db + from services import auth_rate_limit + + monkeypatch.setattr(auth_rate_limit, "PASSWORD_RESET_CONFIRM_LIMIT_PER_IP", 2) + monkeypatch.setattr(auth_rate_limit, "PASSWORD_RESET_CONFIRM_LIMIT_PER_ACCOUNT_IP", 2) + monkeypatch.setattr(auth_rate_limit, "MAX_AUTH_RATE_LIMIT_BUCKETS", 3) + + token_a = "A" * 43 + token_b = "B" * 43 + assert client.post( + "/api/v1/auth/password-reset/confirm", + json={"token": token_a, "newPassword": "ValidPassword123!"}, + ).status_code == 400 + assert client.post( + "/api/v1/auth/password-reset/confirm", + json={"token": token_b, "newPassword": "ValidPassword123!"}, + ).status_code == 400 + throttled = client.post( + "/api/v1/auth/password-reset/confirm", + json={"token": token_a, "newPassword": "ValidPassword123!"}, + ) + assert throttled.status_code == 429 + assert int(throttled.headers["retry-after"]) >= 1 + + conn = get_db() + try: + count = conn.execute("SELECT COUNT(*) FROM auth_rate_limits").fetchone()[0] + assert count <= 3 + finally: + conn.close() + + +def test_trusted_proxy_cidrs_isolate_client_ips_for_auth_rate_limiting(monkeypatch): + from starlette.requests import Request + from core.rate_limit import extract_client_ip + from services import auth_rate_limit + + def make_request(peer: str, xff=None) -> Request: + headers = [] + if xff is not None: + headers.append((b"x-forwarded-for", xff.encode("latin-1"))) + scope = { + "type": "http", + "method": "POST", + "path": "/api/v1/auth/register", + "headers": headers, + "client": (peer, 12345), + } + return Request(scope) + + monkeypatch.delenv("FABLE_TRUSTED_PROXY_CIDRS", raising=False) + assert extract_client_ip(make_request("172.29.241.2", "198.51.100.10")) == "172.29.241.2" + + monkeypatch.setenv("FABLE_TRUSTED_PROXY_CIDRS", "172.29.241.0/29") + assert extract_client_ip(make_request("172.29.241.2", "198.51.100.10, 172.29.241.2")) == "198.51.100.10" + assert extract_client_ip(make_request("192.0.2.55", "198.51.100.10")) == "192.0.2.55" + + monkeypatch.setattr(auth_rate_limit, "REGISTER_LIMIT_PER_IP", 1) + auth_rate_limit.enforce_auth_rate_limit("register", "198.51.100.1") + auth_rate_limit.enforce_auth_rate_limit("register", "198.51.100.2") + with pytest.raises(Exception) as exc: + auth_rate_limit.enforce_auth_rate_limit("register", "198.51.100.1") + assert getattr(exc.value, "status_code", None) == 429 + + +def test_unique_handles_and_reserved_catalog_author_impersonation_blocked(tmp_path, monkeypatch): + import sqlite3 + from core.database import init_db + + first_headers = auth_headers("First Writer") + second_headers = auth_headers("Second Writer") + + r1 = client.patch( + "/api/v1/auth/me", + headers=first_headers, + json={"name": "First Writer", "handle": "unique_scribe", "bio": ""}, + ) + assert r1.status_code == 200 + + dup_update = client.patch( + "/api/v1/auth/me", + headers=second_headers, + json={"name": "Second Writer", "handle": "UNIQUE_SCRIBE", "bio": ""}, + ) + assert dup_update.status_code == 409 + + dup_register = client.post( + "/api/v1/auth/register", + json={ + "email": f"{uuid4()}@example.test", + "password": "LongSecurePassword123!", + "name": "Third Writer", + "handle": "@unique_scribe", + }, + ) + assert dup_register.status_code == 409 + + reserved_name = client.post( + "/api/v1/auth/register", + json={ + "email": f"{uuid4()}@example.test", + "password": "LongSecurePassword123!", + "name": "Aesop", + "handle": "new_scribe_1", + }, + ) + assert reserved_name.status_code == 400 + + reserved_update = client.patch( + "/api/v1/auth/me", + headers=second_headers, + json={"name": "Second Writer", "handle": "jane austen", "bio": ""}, + ) + assert reserved_update.status_code == 400 + + legacy_db = tmp_path / "legacy-handles.sqlite3" + monkeypatch.setenv("FABLE_DB_PATH", str(legacy_db)) + init_db() + with sqlite3.connect(legacy_db) as raw: + raw.execute("DROP INDEX idx_users_handle_lower") + raw.execute( + """INSERT INTO users (id, email, password_hash, name, handle, bio, created_at_utc, updated_at_utc) + VALUES ('u1', 'a@example.test', 'h', 'A', '@shared', '', '2026-01-01T00:00:00Z', '2026-01-01T00:00:00Z'), + ('u2', 'b@example.test', 'h', 'B', '@SHARED', '', '2026-01-02T00:00:00Z', '2026-01-02T00:00:00Z')""" + ) + raw.commit() + init_db() + with sqlite3.connect(legacy_db) as raw: + handles = [r[0] for r in raw.execute("SELECT handle FROM users ORDER BY id").fetchall()] + assert handles[0] == "@shared" + assert handles[1] != "@SHARED" and handles[1].startswith("@SHARED_") + + +def test_read_only_requests_use_in_memory_rate_limiter_without_shared_db_writes(monkeypatch): + from core.rate_limit import limiter + + limiter.reset() + monkeypatch.setenv("FABLE_RATE_LIMIT_ENABLED", "true") + + db_calls = [] + original_is_allowed = limiter.is_allowed + + def tracked_is_allowed(client_id: str, tier: str = "general"): + db_calls.append((client_id, tier)) + return original_is_allowed(client_id, tier) + + monkeypatch.setattr(limiter, "is_allowed", tracked_is_allowed) + + assert client.get("/api/v1/stories").status_code == 200 + assert client.get("/api/v1/genres").status_code == 200 + assert db_calls == [] + + client.post("/api/v1/auth/logout") + assert len(db_calls) == 1 + limiter.reset() + + +def test_story_listing_computes_shelf_counts_in_single_query(): + writer_headers = auth_headers("Metric Author") + created = client.post( + "/api/v1/stories", + headers=writer_headers, + json={ + "title": "Single Query Metrics", + "genre": "Folklore", + "synopsis": "Tests joined shelf counts.", + "content": "Story content.", + }, + ) + assert created.status_code == 201 + story_id = created.json()["id"] + assert created.json()["ownerUserId"] is not None + + reader_headers = auth_headers("Metric Reader") + sync = client.post( + "/api/v1/shelf/sync", + headers=reader_headers, + json={ + "deviceId": str(uuid4()), + "items": [ + { + "storyId": story_id, + "readingProgress": 0.5, + "isBookmarked": True, + "isCompleted": False, + "updatedAtUtc": "2026-10-01T00:00:00Z", + } + ], + }, + ) + assert sync.status_code == 200 + + stories_res = client.get("/api/v1/stories") + assert stories_res.status_code == 200 + matched = [s for s in stories_res.json() if s["id"] == story_id] + assert len(matched) == 1 + assert matched[0]["savesCount"] == "1" + assert matched[0]["readsCount"] == "1" + + +def test_gutenberg_authors_cache_reuses_snapshot_until_invalidated(monkeypatch): + import asyncio + from services import gutenberg, story_service + + entries = [ + gutenberg.GutenbergCatalogEntry(1342, "Pride and Prejudice", "Austen, Jane", "Fiction", "", "en"), + ] + load_calls = 0 + + async def fake_load(_client): + nonlocal load_calls + load_calls += 1 + return entries + + gutenberg.invalidate_gutenberg_authors_cache() + monkeypatch.setattr(gutenberg, "_load_gutenberg_catalog", fake_load) + + first = asyncio.run(gutenberg.get_gutenberg_authors(limit=5)) + second = asyncio.run(gutenberg.get_gutenberg_authors(limit=5)) + assert first == second + assert load_calls == 2 + assert gutenberg._GUTENBERG_AUTHORS_CACHE is not None + + story_service.invalidate_top_authors_cache() + assert gutenberg._GUTENBERG_AUTHORS_CACHE is None + + +def test_story_owner_update_delete_and_author_name_sync(): + owner_headers = auth_headers("Initial Pen Name") + other_headers = auth_headers("Other User") + + created = client.post( + "/api/v1/stories", + headers=owner_headers, + json={ + "title": "Original Title", + "genre": "Folklore", + "chapter": "Chapter 1", + "synopsis": "Original synopsis", + "content": "Original body words here.", + "readTimeMinutes": 2, + }, + ) + assert created.status_code == 201 + story_id = created.json()["id"] + + assert client.patch( + f"/api/v1/stories/{story_id}", + headers=other_headers, + json={"title": "Hijacked"}, + ).status_code == 403 + assert client.delete(f"/api/v1/stories/{story_id}", headers=other_headers).status_code == 403 + + updated = client.patch( + f"/api/v1/stories/{story_id}", + headers=owner_headers, + json={"title": "Revised Title", "content": "Updated body text."}, + ) + assert updated.status_code == 200 + assert updated.json()["title"] == "Revised Title" + assert updated.json()["content"] == "Updated body text." + assert updated.json()["chapters"][0]["content"] == "Updated body text." + + profile_res = client.patch( + "/api/v1/auth/me", + headers=owner_headers, + json={"name": "Updated Pen Name", "handle": "updated_pen", "bio": "Writer"}, + ) + assert profile_res.status_code == 200 + story_after_rename = client.get(f"/api/v1/stories/{story_id}") + assert story_after_rename.status_code == 200 + assert story_after_rename.json()["author"] == "Updated Pen Name" + + assert client.delete(f"/api/v1/stories/{story_id}", headers=owner_headers).status_code == 204 + assert client.get(f"/api/v1/stories/{story_id}").status_code == 404 + + +def test_account_deletion_cascades_user_stories_sessions_and_shelf(): + email = f"{uuid4()}@example.test" + password = "StrongDeletePass123!" + reg = client.post( + "/api/v1/auth/register", + json={"email": email, "password": password, "name": "Doomed Writer", "handle": "doomed_writer"}, + ) + assert reg.status_code == 201 + token = reg.json()["accessToken"] + headers = {"Authorization": f"Bearer {token}"} + + story_res = client.post( + "/api/v1/stories", + headers=headers, + json={ + "title": "Ephemeral Tale", + "genre": "Gothic", + "synopsis": "Deleted with account.", + "content": "Gone soon.", + }, + ) + assert story_res.status_code == 201 + story_id = story_res.json()["id"] + + shelf_res = client.post( + "/api/v1/shelf/sync", + headers=headers, + json={ + "deviceId": str(uuid4()), + "items": [ + { + "storyId": story_id, + "readingProgress": 1.0, + "isBookmarked": True, + "isCompleted": True, + "updatedAtUtc": "2026-10-01T00:00:00Z", + } + ], + }, + ) + assert shelf_res.status_code == 200 + + delete_res = client.delete("/api/v1/auth/me", headers=headers) + assert delete_res.status_code == 204 + assert client.get("/api/v1/auth/me", headers=headers).status_code == 401 + assert client.get(f"/api/v1/stories/{story_id}").status_code == 404 + assert client.post("/api/v1/auth/login", json={"email": email, "password": password}).status_code == 401 From 9920a4ed05ef9314473540423775835f427b0211 Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 4/9] feat(ios): harden SwiftData recovery, consolidate shelf state, and wire lifecycle APIs --- .../Features/Auth/Services/AuthManager.swift | 53 ++- .../Features/Library/Models/Story.swift | 8 +- .../Features/Library/Models/StoryEntity.swift | 43 +++ .../Library/Services/PersistenceService.swift | 317 +++++++++++++++++- .../Library/Services/StoryAPIService.swift | 107 ++++++ .../Library/ViewModels/StoryStore.swift | 182 +++++++--- 6 files changed, 638 insertions(+), 72 deletions(-) diff --git a/frontend/FableApp/Features/Auth/Services/AuthManager.swift b/frontend/FableApp/Features/Auth/Services/AuthManager.swift index b428c49..7777c59 100644 --- a/frontend/FableApp/Features/Auth/Services/AuthManager.swift +++ b/frontend/FableApp/Features/Auth/Services/AuthManager.swift @@ -225,6 +225,7 @@ public final class AuthManager: ObservableObject { public func updateProfile(name: String, handle: String, bio: String, avatarName: String? = nil) async -> Bool { guard var session = currentSession else { return false } + let previousSession = session let cleanName = name.trimmingCharacters(in: .whitespacesAndNewlines) guard !cleanName.isEmpty else { authErrorMessage = "Display name cannot be blank." @@ -256,13 +257,53 @@ public final class AuthManager: ObservableObject { } guard persistSession(updatedSession, accessToken: token) else { return false } UserDefaults.standard.removeObject(forKey: pendingKey) + authErrorMessage = nil return true + } catch let error as APIRequestError { + _ = persistSession(previousSession, accessToken: token) + UserDefaults.standard.removeObject(forKey: pendingKey) + authErrorMessage = error.message + return false } catch { authErrorMessage = "Profile saved locally and queued to sync when online." return true } } + public func deleteAccount() async -> Bool { + guard let session = currentSession, !session.isGuest, + let token = keychain.readAccessToken() else { + authErrorMessage = "Sign in again to delete this account." + return false + } + + do { + try await apiService.deleteAccount(token: token) + clearLocalSessionState(for: session.id) + return true + } catch let error as APIRequestError { + authErrorMessage = error.message + return false + } catch { + authErrorMessage = "Unable to delete account right now. Please try again." + return false + } + } + + private func clearLocalSessionState(for userId: UUID?) { + if let userId { + UserDefaults.standard.removeObject(forKey: pendingProfileKeyPrefix + userId.uuidString) + } + keychain.deleteData(key: "userSession") + keychain.deleteAccessToken() + UserDefaults.standard.removeObject(forKey: sessionStorageKey) + self.currentSession = nil + self.isAuthenticated = false + self.isGuestMode = false + self.authErrorMessage = nil + AuthViewModel.shared.adoptSignedOutState() + } + public func syncPendingProfile() async { guard let session = currentSession, !session.isGuest, let token = keychain.readAccessToken() else { return } @@ -284,16 +325,6 @@ public final class AuthManager: ObservableObject { let token = keychain.readAccessToken() { Task { try? await apiService.logout(token: token) } } - if let session = currentSession { - UserDefaults.standard.removeObject(forKey: pendingProfileKeyPrefix + session.id.uuidString) - } - keychain.deleteData(key: "userSession") - keychain.deleteAccessToken() - UserDefaults.standard.removeObject(forKey: sessionStorageKey) - self.currentSession = nil - self.isAuthenticated = false - self.isGuestMode = false - self.authErrorMessage = nil - AuthViewModel.shared.adoptSignedOutState() + clearLocalSessionState(for: currentSession?.id) } } diff --git a/frontend/FableApp/Features/Library/Models/Story.swift b/frontend/FableApp/Features/Library/Models/Story.swift index d78f47d..5be048e 100644 --- a/frontend/FableApp/Features/Library/Models/Story.swift +++ b/frontend/FableApp/Features/Library/Models/Story.swift @@ -282,6 +282,7 @@ public struct Story: Identifiable, Hashable, Codable { public var contentFormat: ContentFormat public var sourceProvider: SourceProvider public var providerId: String? + public var ownerUserId: UUID? public var lastReadChapterId: String? public var lastReadChapterNumber: Int? @@ -332,7 +333,7 @@ public struct Story: Identifiable, Hashable, Codable { case id, title, author, genre, synopsis, content, readTimeMinutes, isBookmarked, isCompleted, createdAtUtc case coverImageName, heroImageName, coverImageUrl, totalPages, currentPage, progressPercent, rating, providerDownloadCount, savesCount, readsCount case isTaleOfTheDay, isRecentSubmission, isCuratorSpotlight, badgeText, totalChapters, chapters - case contentFormat, sourceProvider, providerId, lastReadChapterId, lastReadChapterNumber + case contentFormat, sourceProvider, providerId, ownerUserId, lastReadChapterId, lastReadChapterNumber } public init(from decoder: Decoder) throws { @@ -367,6 +368,7 @@ public struct Story: Identifiable, Hashable, Codable { self.contentFormat = try container.decodeIfPresent(ContentFormat.self, forKey: .contentFormat) ?? .prose self.sourceProvider = try container.decodeIfPresent(SourceProvider.self, forKey: .sourceProvider) ?? .fableOriginal self.providerId = try container.decodeIfPresent(String.self, forKey: .providerId) + self.ownerUserId = try container.decodeIfPresent(UUID.self, forKey: .ownerUserId) self.lastReadChapterId = try container.decodeIfPresent(String.self, forKey: .lastReadChapterId) self.lastReadChapterNumber = try container.decodeIfPresent(Int.self, forKey: .lastReadChapterNumber) } @@ -386,6 +388,7 @@ public struct Story: Identifiable, Hashable, Codable { contentFormat: ContentFormat = .prose, sourceProvider: SourceProvider = .fableOriginal, providerId: String? = nil, + ownerUserId: UUID? = nil, lastReadChapterId: String? = nil, lastReadChapterNumber: Int? = nil ) { @@ -418,6 +421,7 @@ public struct Story: Identifiable, Hashable, Codable { self.contentFormat = contentFormat self.sourceProvider = sourceProvider self.providerId = providerId + self.ownerUserId = ownerUserId self.lastReadChapterId = lastReadChapterId self.lastReadChapterNumber = lastReadChapterNumber } @@ -450,6 +454,7 @@ public struct Story: Identifiable, Hashable, Codable { contentFormat: ContentFormat = .prose, sourceProvider: SourceProvider = .fableOriginal, providerId: String? = nil, + ownerUserId: UUID? = nil, chapters: [Chapter]? = nil, lastReadChapterId: String? = nil, lastReadChapterNumber: Int? = nil @@ -483,6 +488,7 @@ public struct Story: Identifiable, Hashable, Codable { self.contentFormat = contentFormat self.sourceProvider = sourceProvider self.providerId = providerId + self.ownerUserId = ownerUserId self.lastReadChapterId = lastReadChapterId self.lastReadChapterNumber = lastReadChapterNumber } diff --git a/frontend/FableApp/Features/Library/Models/StoryEntity.swift b/frontend/FableApp/Features/Library/Models/StoryEntity.swift index ff9e44d..fe49d60 100644 --- a/frontend/FableApp/Features/Library/Models/StoryEntity.swift +++ b/frontend/FableApp/Features/Library/Models/StoryEntity.swift @@ -20,6 +20,7 @@ public final class StoryEntity { public var heroImageName: String? public var coverImageUrl: String? public var providerId: String? + public var ownerUserId: UUID? public var providerDownloadCount: Int? @Attribute(.externalStorage) public var cachedChaptersData: Data? public var lastReadChapterId: String? @@ -50,6 +51,7 @@ public final class StoryEntity { heroImageName: String? = nil, coverImageUrl: String? = nil, providerId: String? = nil, + ownerUserId: UUID? = nil, providerDownloadCount: Int? = nil, cachedChaptersData: Data? = nil, lastReadChapterId: String? = nil, @@ -76,6 +78,7 @@ public final class StoryEntity { self.heroImageName = heroImageName self.coverImageUrl = coverImageUrl self.providerId = providerId + self.ownerUserId = ownerUserId self.providerDownloadCount = providerDownloadCount self.cachedChaptersData = cachedChaptersData self.lastReadChapterId = lastReadChapterId @@ -154,3 +157,43 @@ public final class ReadingLogEntity { self.isCompleted = isCompleted } } + +@Model +public final class ShelfItemEntity { + @Attribute(.unique) public var compositeKey: String + public var ownerKey: String + public var storyId: UUID + public var readingProgress: Double + public var isBookmarked: Bool + public var isCompleted: Bool + public var currentPage: Int + public var totalPages: Int + public var lastReadChapterId: String? + public var lastReadChapterNumber: Int? + public var updatedAtUtc: Date + + public init( + ownerKey: String, + storyId: UUID, + readingProgress: Double = 0.0, + isBookmarked: Bool = false, + isCompleted: Bool = false, + currentPage: Int = 1, + totalPages: Int = 1, + lastReadChapterId: String? = nil, + lastReadChapterNumber: Int? = nil, + updatedAtUtc: Date = Date() + ) { + self.compositeKey = "\(ownerKey)::\(storyId.uuidString.lowercased())" + self.ownerKey = ownerKey + self.storyId = storyId + self.readingProgress = min(1.0, max(0.0, readingProgress)) + self.isBookmarked = isBookmarked + self.isCompleted = isCompleted + self.currentPage = max(1, currentPage) + self.totalPages = max(1, totalPages) + self.lastReadChapterId = lastReadChapterId + self.lastReadChapterNumber = lastReadChapterNumber + self.updatedAtUtc = updatedAtUtc + } +} diff --git a/frontend/FableApp/Features/Library/Services/PersistenceService.swift b/frontend/FableApp/Features/Library/Services/PersistenceService.swift index fd9ce53..fbf4dd7 100644 --- a/frontend/FableApp/Features/Library/Services/PersistenceService.swift +++ b/frontend/FableApp/Features/Library/Services/PersistenceService.swift @@ -7,31 +7,120 @@ public final class PersistenceService { public static let shared = PersistenceService() public let container: ModelContainer + public private(set) var didRecoverStoreByReset: Bool = false + public private(set) var isUsingInMemoryFallback: Bool = false + public var context: ModelContext { container.mainContext } - - public init() { - // Guarantee Application Support directory exists to prevent CoreData recovery warnings - if let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first { + + public static var defaultSchema: Schema { + Schema([ + StoryEntity.self, + AnnotationEntity.self, + ReadingLogEntity.self, + ShelfItemEntity.self + ]) + } + + public struct ResilientContainerResult { + public let container: ModelContainer + public let didRecoverByReset: Bool + public let isInMemoryFallback: Bool + } + + private static func removeSQLiteStoreArtifacts(at storeURL: URL) { + let fileManager = FileManager.default + let candidateURLs = [ + storeURL, + URL(fileURLWithPath: storeURL.path + "-wal"), + URL(fileURLWithPath: storeURL.path + "-shm") + ] + for url in candidateURLs where fileManager.fileExists(atPath: url.path) { + try? fileManager.removeItem(at: url) + } + } + + private static func defaultStoreURLs() -> [URL] { + guard let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { + return [] + } + return [appSupportURL.appendingPathComponent("default.store")] + } + + public static func makeResilientContainer( + schema: Schema? = nil, + storeURL: URL? = nil, + isStoredInMemoryOnly: Bool = false, + containerBuilder: ((Schema, ModelConfiguration) throws -> ModelContainer)? = nil + ) -> ResilientContainerResult { + let resolvedSchema = schema ?? Self.defaultSchema + let build: (Schema, ModelConfiguration) throws -> ModelContainer = containerBuilder ?? { schema, configuration in + try ModelContainer(for: schema, configurations: [configuration]) + } + + if let storeURL { + let parent = storeURL.deletingLastPathComponent() + if !FileManager.default.fileExists(atPath: parent.path) { + try? FileManager.default.createDirectory(at: parent, withIntermediateDirectories: true, attributes: nil) + } + } else if let appSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first { if !FileManager.default.fileExists(atPath: appSupportURL.path) { try? FileManager.default.createDirectory(at: appSupportURL, withIntermediateDirectories: true, attributes: nil) } } - + + if isStoredInMemoryOnly { + let memoryConfig = ModelConfiguration(schema: resolvedSchema, isStoredInMemoryOnly: true) + if let memoryContainer = try? build(resolvedSchema, memoryConfig) { + return ResilientContainerResult(container: memoryContainer, didRecoverByReset: false, isInMemoryFallback: true) + } + } + + let persistentConfig: ModelConfiguration = { + if let storeURL { + return ModelConfiguration(schema: resolvedSchema, url: storeURL) + } + return ModelConfiguration(schema: resolvedSchema, isStoredInMemoryOnly: false) + }() + do { - let schema = Schema([ - StoryEntity.self, - AnnotationEntity.self, - ReadingLogEntity.self - ]) - let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false) - self.container = try ModelContainer(for: schema, configurations: [configuration]) + let container = try build(resolvedSchema, persistentConfig) + return ResilientContainerResult(container: container, didRecoverByReset: false, isInMemoryFallback: false) } catch { - fatalError("Failed to initialize SwiftData ModelContainer: \(error)") + print("Primary SwiftData ModelContainer load failed (\(error)). Attempting local store reset.") + let targets = storeURL.map { [$0] } ?? defaultStoreURLs() + for targetURL in targets { + removeSQLiteStoreArtifacts(at: targetURL) + } + + do { + let recoveredContainer = try build(resolvedSchema, persistentConfig) + return ResilientContainerResult(container: recoveredContainer, didRecoverByReset: true, isInMemoryFallback: false) + } catch { + print("Recovered persistent SwiftData ModelContainer failed (\(error)). Falling back to in-memory store.") + let fallbackConfig = ModelConfiguration(schema: resolvedSchema, isStoredInMemoryOnly: true) + do { + let memoryContainer = try build(resolvedSchema, fallbackConfig) + return ResilientContainerResult(container: memoryContainer, didRecoverByReset: true, isInMemoryFallback: true) + } catch { + preconditionFailure("Unable to initialize even an in-memory SwiftData ModelContainer: \(error)") + } + } } } + public init(storeURL: URL? = nil, isStoredInMemoryOnly: Bool = false) { + let result = Self.makeResilientContainer( + schema: Self.defaultSchema, + storeURL: storeURL, + isStoredInMemoryOnly: isStoredInMemoryOnly + ) + self.container = result.container + self.didRecoverStoreByReset = result.didRecoverByReset + self.isUsingInMemoryFallback = result.isInMemoryFallback + } + public static let legacyDemoStoryIds: Set = [ UUID(uuidString: "66666666-6666-6666-6666-666666666666")!, UUID(uuidString: "77777777-7777-7777-7777-777777777777")!, @@ -114,6 +203,7 @@ public final class PersistenceService { existing.heroImageName = story.heroImageName existing.coverImageUrl = story.coverImageUrl if let providerId = story.providerId { existing.providerId = providerId } + if let ownerUserId = story.ownerUserId { existing.ownerUserId = ownerUserId } if let providerDownloadCount = story.providerDownloadCount { existing.providerDownloadCount = providerDownloadCount } @@ -144,6 +234,7 @@ public final class PersistenceService { heroImageName: story.heroImageName, coverImageUrl: story.coverImageUrl, providerId: story.providerId, + ownerUserId: story.ownerUserId, providerDownloadCount: story.providerDownloadCount, cachedChaptersData: encodedChapters(story.chapters), lastReadChapterId: story.lastReadChapterId, @@ -463,4 +554,204 @@ public final class PersistenceService { return ReadingStatsSummary(storiesReadCount: 0, totalMinutesRead: 0, streakDays: 0) } } + + // MARK: - SwiftData Shelf State (IOS-02) + + public struct ShelfStateRecord: Codable, Equatable { + public let storyId: UUID + public let readingProgress: Double + public let isBookmarked: Bool + public let isCompleted: Bool + public let currentPage: Int + public let totalPages: Int + public let lastReadChapterId: String? + public let lastReadChapterNumber: Int? + public let updatedAtUtc: Date + + public init( + storyId: UUID, + readingProgress: Double, + isBookmarked: Bool, + isCompleted: Bool, + currentPage: Int, + totalPages: Int, + lastReadChapterId: String?, + lastReadChapterNumber: Int?, + updatedAtUtc: Date + ) { + self.storyId = storyId + self.readingProgress = readingProgress + self.isBookmarked = isBookmarked + self.isCompleted = isCompleted + self.currentPage = currentPage + self.totalPages = totalPages + self.lastReadChapterId = lastReadChapterId + self.lastReadChapterNumber = lastReadChapterNumber + self.updatedAtUtc = updatedAtUtc + } + } + + public func fetchShelfStates(ownerKey: String) -> [UUID: ShelfStateRecord] { + let descriptor = FetchDescriptor( + predicate: #Predicate { $0.ownerKey == ownerKey } + ) + do { + let entities = try context.fetch(descriptor) + var result: [UUID: ShelfStateRecord] = [:] + for entity in entities { + result[entity.storyId] = ShelfStateRecord( + storyId: entity.storyId, + readingProgress: entity.readingProgress, + isBookmarked: entity.isBookmarked, + isCompleted: entity.isCompleted, + currentPage: entity.currentPage, + totalPages: entity.totalPages, + lastReadChapterId: entity.lastReadChapterId, + lastReadChapterNumber: entity.lastReadChapterNumber, + updatedAtUtc: entity.updatedAtUtc + ) + } + return result + } catch { + print("Failed to fetch shelf states: \(error)") + return [:] + } + } + + private func apply(_ record: ShelfStateRecord, to entity: ShelfItemEntity) { + entity.readingProgress = min(1.0, max(0.0, record.readingProgress)) + entity.isBookmarked = record.isBookmarked + entity.isCompleted = record.isCompleted + entity.currentPage = max(1, record.currentPage) + entity.totalPages = max(1, record.totalPages) + entity.lastReadChapterId = record.lastReadChapterId + entity.lastReadChapterNumber = record.lastReadChapterNumber + entity.updatedAtUtc = record.updatedAtUtc + } + + private func makeShelfEntity(ownerKey: String, storyId: UUID, record: ShelfStateRecord) -> ShelfItemEntity { + ShelfItemEntity( + ownerKey: ownerKey, + storyId: storyId, + readingProgress: record.readingProgress, + isBookmarked: record.isBookmarked, + isCompleted: record.isCompleted, + currentPage: record.currentPage, + totalPages: record.totalPages, + lastReadChapterId: record.lastReadChapterId, + lastReadChapterNumber: record.lastReadChapterNumber, + updatedAtUtc: record.updatedAtUtc + ) + } + + public func upsertShelfState(_ record: ShelfStateRecord, ownerKey: String) { + let compositeKey = "\(ownerKey)::\(record.storyId.uuidString.lowercased())" + var descriptor = FetchDescriptor( + predicate: #Predicate { $0.compositeKey == compositeKey } + ) + descriptor.fetchLimit = 1 + do { + if let existing = try context.fetch(descriptor).first { + apply(record, to: existing) + } else { + context.insert(makeShelfEntity(ownerKey: ownerKey, storyId: record.storyId, record: record)) + } + try context.save() + } catch { + print("Failed to upsert shelf state: \(error)") + } + } + + public func replaceShelfStates(_ records: [UUID: ShelfStateRecord], ownerKey: String) { + let descriptor = FetchDescriptor( + predicate: #Predicate { $0.ownerKey == ownerKey } + ) + do { + let existing = try context.fetch(descriptor) + var existingByStoryId = Dictionary(uniqueKeysWithValues: existing.map { ($0.storyId, $0) }) + + for (storyId, record) in records { + if let entity = existingByStoryId.removeValue(forKey: storyId) { + apply(record, to: entity) + } else { + context.insert(makeShelfEntity(ownerKey: ownerKey, storyId: storyId, record: record)) + } + } + + for staleEntity in existingByStoryId.values { + context.delete(staleEntity) + } + try context.save() + } catch { + print("Failed to replace shelf states: \(error)") + } + } + + @discardableResult + public func migrateLegacyShelfStatesIfNeeded( + ownerKey: String, + legacyStorageKey: String, + defaults: UserDefaults = .standard + ) -> [UUID: ShelfStateRecord] { + var currentStates = fetchShelfStates(ownerKey: ownerKey) + guard let legacyData = defaults.data(forKey: legacyStorageKey) else { + return currentStates + } + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + if let legacyMap = try? decoder.decode([String: ShelfStateRecord].self, from: legacyData) { + var didMerge = false + for (idString, record) in legacyMap { + guard let uuid = UUID(uuidString: idString) else { continue } + if let existing = currentStates[uuid] { + if record.updatedAtUtc > existing.updatedAtUtc { + currentStates[uuid] = record + didMerge = true + } + } else { + currentStates[uuid] = record + didMerge = true + } + } + if didMerge { + replaceShelfStates(currentStates, ownerKey: ownerKey) + } + } + defaults.removeObject(forKey: legacyStorageKey) + return currentStates + } + + // MARK: - Account Deletion Cleanup (DOM-01) + + public func deleteAccountData(ownerUserId: UUID) { + let ownerKey = ownerUserId.uuidString.lowercased() + do { + let storyEntities = try context.fetch(FetchDescriptor()) + for entity in storyEntities where entity.ownerUserId == ownerUserId { + context.delete(entity) + } + + let annotationEntities = try context.fetch(FetchDescriptor()) + for entity in annotationEntities where entity.ownerUserId == ownerUserId { + context.delete(entity) + } + + let logEntities = try context.fetch(FetchDescriptor()) + for entity in logEntities where entity.ownerUserId == ownerUserId { + context.delete(entity) + } + + let shelfEntities = try context.fetch( + FetchDescriptor(predicate: #Predicate { $0.ownerKey == ownerKey }) + ) + for entity in shelfEntities { + context.delete(entity) + } + + try context.save() + } catch { + print("Failed to delete account persistence data: \(error)") + } + } } diff --git a/frontend/FableApp/Features/Library/Services/StoryAPIService.swift b/frontend/FableApp/Features/Library/Services/StoryAPIService.swift index 1567cb5..775279d 100644 --- a/frontend/FableApp/Features/Library/Services/StoryAPIService.swift +++ b/frontend/FableApp/Features/Library/Services/StoryAPIService.swift @@ -32,6 +32,71 @@ public struct CreateStoryRequest: Codable { self.readTimeMinutes = readTimeMinutes self.contentFormat = contentFormat } + + public static func estimatedReadTimeMinutes(for content: String) -> Int { + let wordCount = content.split { $0.isWhitespace || $0.isNewline }.count + return max(1, wordCount / 150) + } + + public static func validateDraftFields( + title: String, + genre: String, + chapter: String, + synopsis: String, + content: String, + requireContent: Bool + ) -> String? { + guard !title.isEmpty, title.unicodeScalars.count <= maximumTitleLength else { + return "Enter a title with 1 to 120 characters." + } + guard !genre.isEmpty else { + return "Choose or enter a genre." + } + guard genre.unicodeScalars.count <= maximumGenreLength else { + return "Keep the genre to 50 characters or fewer." + } + guard chapter.unicodeScalars.count <= maximumChapterLength else { + return "Keep the chapter title to 120 characters or fewer." + } + guard !synopsis.isEmpty else { + return "Add a synopsis before publishing." + } + guard synopsis.unicodeScalars.count <= maximumSynopsisLength else { + return "Keep the synopsis to 2,000 characters or fewer." + } + if requireContent && content.isEmpty { + return "Add manuscript text before publishing." + } + guard content.unicodeScalars.count <= maximumContentLength else { + return "Keep the manuscript to 50,000 characters or fewer." + } + return nil + } +} + +public struct UpdateStoryRequest: Codable { + public let title: String? + public let genre: String? + public let chapter: String? + public let synopsis: String? + public let content: String? + public let readTimeMinutes: Int? + + public init( + title: String? = nil, + genre: String? = nil, + chapter: String? = nil, + synopsis: String? = nil, + content: String? = nil, + readTimeMinutes: Int? = nil + ) { + self.title = title + self.genre = genre + self.chapter = chapter + self.synopsis = synopsis + self.content = content + self.readTimeMinutes = readTimeMinutes + } } public struct ShelfSyncItem: Codable, Equatable { @@ -200,6 +265,8 @@ public struct AuthTokenResponse: Codable { public protocol StoryAPIServiceProtocol: Sendable { func fetchStories(genre: String?, search: String?, since: Date?) async throws -> [Story] func createStory(_ request: CreateStoryRequest, token: String) async throws -> Story + func updateStory(id: UUID, _ request: UpdateStoryRequest, token: String) async throws -> Story + func deleteStory(id: UUID, token: String) async throws func fetchMyStories(token: String) async throws -> [Story] func syncShelf(deviceId: UUID, token: String, items: [ShelfSyncItem]) async throws -> [ShelfSyncItem] func fetchShelf(deviceId: UUID, token: String) async throws -> [ShelfSyncItem] @@ -216,6 +283,7 @@ public protocol StoryAPIServiceProtocol: Sendable { func confirmPasswordReset(token: String, newPassword: String) async throws func fetchCurrentUser(token: String) async throws -> AuthUserDTO func updateProfile(_ request: ProfileUpdateRequest, token: String) async throws -> AuthUserDTO + func deleteAccount(token: String) async throws func recordReadingSession(_ request: ReadingSessionRequest, token: String) async throws func fetchReadingStats(token: String) async throws -> ReadingStatsDTO func logout(token: String) async throws @@ -335,6 +403,35 @@ public final class StoryAPIService: StoryAPIServiceProtocol { return try decoder.decode(Story.self, from: data) } + public func updateStory(id: UUID, _ request: UpdateStoryRequest, token: String) async throws -> Story { + let url = baseURL.appendingPathComponent("stories").appendingPathComponent(id.uuidString) + var urlRequest = URLRequest(url: url) + urlRequest.httpMethod = "PATCH" + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + urlRequest.httpBody = try encoder.encode(request) + + let (data, response) = try await session.data(for: urlRequest) + try validateResponse(response, data: data) + + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + return try decoder.decode(Story.self, from: data) + } + + public func deleteStory(id: UUID, token: String) async throws { + let url = baseURL.appendingPathComponent("stories").appendingPathComponent(id.uuidString) + var urlRequest = URLRequest(url: url) + urlRequest.httpMethod = "DELETE" + urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + + let (data, response) = try await session.data(for: urlRequest) + try validateResponse(response, data: data) + } + public func fetchMyStories(token: String) async throws -> [Story] { let url = baseURL.appendingPathComponent("auth").appendingPathComponent("me").appendingPathComponent("stories") var request = URLRequest(url: url) @@ -833,6 +930,16 @@ public final class StoryAPIService: StoryAPIServiceProtocol { return try decoder.decode(AuthUserDTO.self, from: data) } + public func deleteAccount(token: String) async throws { + let url = baseURL.appendingPathComponent("auth").appendingPathComponent("me") + var urlRequest = URLRequest(url: url) + urlRequest.httpMethod = "DELETE" + urlRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + + let (data, response) = try await session.data(for: urlRequest) + try validateResponse(response, data: data) + } + public func fetchCurrentUser(token: String) async throws -> AuthUserDTO { let url = baseURL.appendingPathComponent("auth").appendingPathComponent("me") var request = URLRequest(url: url) diff --git a/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift b/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift index 3c2d08f..2ae7e68 100644 --- a/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift +++ b/frontend/FableApp/Features/Library/ViewModels/StoryStore.swift @@ -184,6 +184,31 @@ public final class StoryStore: ObservableObject { self.lastReadChapterNumber = previous.lastReadChapterNumber self.updatedAtUtc = syncItem.updatedAtUtc } + + init(record: PersistenceService.ShelfStateRecord) { + self.readingProgress = record.readingProgress + self.isBookmarked = record.isBookmarked + self.isCompleted = record.isCompleted + self.currentPage = record.currentPage + self.totalPages = record.totalPages + self.lastReadChapterId = record.lastReadChapterId + self.lastReadChapterNumber = record.lastReadChapterNumber + self.updatedAtUtc = record.updatedAtUtc + } + + func record(storyId: UUID) -> PersistenceService.ShelfStateRecord { + PersistenceService.ShelfStateRecord( + storyId: storyId, + readingProgress: readingProgress, + isBookmarked: isBookmarked, + isCompleted: isCompleted, + currentPage: currentPage, + totalPages: totalPages, + lastReadChapterId: lastReadChapterId, + lastReadChapterNumber: lastReadChapterNumber, + updatedAtUtc: updatedAtUtc + ) + } } private struct WriterDraft: Codable { @@ -325,36 +350,15 @@ public final class StoryStore: ObservableObject { let synopsis = draftSynopsis.trimmingCharacters(in: .whitespacesAndNewlines) let manuscript = draftManuscript.trimmingCharacters(in: .whitespacesAndNewlines) - guard !title.isEmpty, title.unicodeScalars.count <= CreateStoryRequest.maximumTitleLength else { - publishErrorMessage = "Enter a title with 1 to 120 characters." - return nil - } - guard !genre.isEmpty else { - publishErrorMessage = "Choose or enter a genre." - return nil - } - guard genre.unicodeScalars.count <= CreateStoryRequest.maximumGenreLength else { - publishErrorMessage = "Keep the genre to 50 characters or fewer." - return nil - } - guard chapter.unicodeScalars.count <= CreateStoryRequest.maximumChapterLength else { - publishErrorMessage = "Keep the chapter title to 120 characters or fewer." - return nil - } - guard !synopsis.isEmpty else { - publishErrorMessage = "Add a synopsis before publishing." - return nil - } - guard synopsis.unicodeScalars.count <= CreateStoryRequest.maximumSynopsisLength else { - publishErrorMessage = "Keep the synopsis to 2,000 characters or fewer." - return nil - } - guard !manuscript.isEmpty else { - publishErrorMessage = "Add manuscript text before publishing." - return nil - } - guard manuscript.unicodeScalars.count <= CreateStoryRequest.maximumContentLength else { - publishErrorMessage = "Keep the manuscript to 50,000 characters or fewer." + if let validationError = CreateStoryRequest.validateDraftFields( + title: title, + genre: genre, + chapter: chapter, + synopsis: synopsis, + content: manuscript, + requireContent: true + ) { + publishErrorMessage = validationError return nil } guard let session = AuthManager.shared.currentSession, !session.isGuest, @@ -371,7 +375,7 @@ public final class StoryStore: ObservableObject { chapter: chapter, synopsis: synopsis, content: manuscript, - readTimeMinutes: max(1, draftWordCount / 150) + readTimeMinutes: CreateStoryRequest.estimatedReadTimeMinutes(for: manuscript) ) do { @@ -432,6 +436,61 @@ public final class StoryStore: ObservableObject { } } + func updatePublishedStory(id: UUID, request: UpdateStoryRequest) async -> Story? { + guard let session = AuthManager.shared.currentSession, !session.isGuest, + let token = KeychainStore.shared.readAccessToken() else { + publishErrorMessage = "Sign in to update your published story." + return nil + } + + do { + var updatedStory = try await apiService.updateStory(id: id, request, token: token) + if let existingState = loadShelfStateCache()[updatedStory.id.uuidString] { + applyShelfState(existingState, to: &updatedStory) + } + if let idx = stories.firstIndex(where: { $0.id == updatedStory.id }) { + stories[idx] = updatedStory + } + if let idx = profileStories.firstIndex(where: { $0.id == updatedStory.id }) { + profileStories[idx] = updatedStory + } + PersistenceService.shared.saveStory(updatedStory) + persistProfileStoriesCache(profileStories, for: session.id) + publishErrorMessage = nil + return updatedStory + } catch let error as APIRequestError { + publishErrorMessage = error.message + return nil + } catch { + publishErrorMessage = "Could not update story. Check your connection and try again." + return nil + } + } + + func deletePublishedStory(id: UUID) async -> Bool { + guard let session = AuthManager.shared.currentSession, !session.isGuest, + let token = KeychainStore.shared.readAccessToken() else { + publishErrorMessage = "Sign in to delete your published story." + return false + } + + do { + try await apiService.deleteStory(id: id, token: token) + stories.removeAll { $0.id == id } + profileStories.removeAll { $0.id == id } + PersistenceService.shared.deleteStory(storyId: id) + persistProfileStoriesCache(profileStories, for: session.id) + publishErrorMessage = nil + return true + } catch let error as APIRequestError { + publishErrorMessage = error.message + return false + } catch { + publishErrorMessage = "Could not delete story. Check your connection and try again." + return false + } + } + private func syncWithPersistence() { // Hydrate and reconcile from SQLite let persisted = PersistenceService.shared.fetchAllStories() @@ -463,6 +522,7 @@ public final class StoryStore: ObservableObject { stories[idx].heroImageName = nil stories[idx].coverImageUrl = validCoverImageURL(entity.coverImageUrl) stories[idx].providerId = entity.providerId + stories[idx].ownerUserId = entity.ownerUserId stories[idx].providerDownloadCount = entity.providerDownloadCount stories[idx].contentFormat = ContentFormat(rawValue: entity.contentFormatRaw ?? "PROSE") ?? .prose stories[idx].sourceProvider = SourceProvider(rawValue: entity.sourceProviderRaw ?? "FABLE_ORIGINAL") ?? .fableOriginal @@ -514,6 +574,7 @@ public final class StoryStore: ObservableObject { contentFormat: ContentFormat(rawValue: entity.contentFormatRaw ?? "PROSE") ?? .prose, sourceProvider: provider, providerId: entity.providerId, + ownerUserId: entity.ownerUserId, chapters: validInitial, lastReadChapterId: entity.lastReadChapterId, lastReadChapterNumber: entity.lastReadChapterNumber @@ -665,9 +726,11 @@ public final class StoryStore: ObservableObject { stories[index].coverImageName = nil stories[index].heroImageName = nil } + if !remote.author.isEmpty { stories[index].author = remote.author } stories[index].totalChapters = remote.totalChapters stories[index].contentFormat = remote.contentFormat stories[index].sourceProvider = remote.sourceProvider + if let ownerUserId = remote.ownerUserId { stories[index].ownerUserId = ownerUserId } if let badge = remote.badgeText { stories[index].badgeText = badge } if let downloadCount = remote.providerDownloadCount { stories[index].providerDownloadCount = downloadCount } if let providerId = remote.providerId { stories[index].providerId = providerId } @@ -852,7 +915,7 @@ public final class StoryStore: ObservableObject { func stories(for writer: Writer) -> [Story] { stories - .filter { matchesAuthor(storyAuthor: $0.author, writerName: writer.name) } + .filter { $0.ownerUserId == nil && matchesAuthor(storyAuthor: $0.author, writerName: writer.name) } .sorted { ($0.providerDownloadCount ?? 0) > ($1.providerDownloadCount ?? 0) } } @@ -1043,23 +1106,37 @@ public final class StoryStore: ObservableObject { "fable_shelf_state_\(activeShelfOwnerKey)" } + private var normalizedShelfOwnerKey: String { + activeShelfOwnerKey.lowercased() + } + private func loadShelfStateCache() -> [String: LocalShelfState] { - guard let data = UserDefaults.standard.data(forKey: shelfStateStorageKey), - let states = try? JSONDecoder().decode([String: LocalShelfState].self, from: data) else { - return [:] + let records = PersistenceService.shared.migrateLegacyShelfStatesIfNeeded( + ownerKey: normalizedShelfOwnerKey, + legacyStorageKey: shelfStateStorageKey + ) + var states: [String: LocalShelfState] = [:] + for (storyId, record) in records { + states[storyId.uuidString] = LocalShelfState(record: record) } return states } private func saveShelfStateCache(_ states: [String: LocalShelfState]) { - guard let data = try? JSONEncoder().encode(states) else { return } - UserDefaults.standard.set(data, forKey: shelfStateStorageKey) + var records: [UUID: PersistenceService.ShelfStateRecord] = [:] + for (storyID, state) in states { + guard let uuid = UUID(uuidString: storyID) else { continue } + records[uuid] = state.record(storyId: uuid) + } + PersistenceService.shared.replaceShelfStates(records, ownerKey: normalizedShelfOwnerKey) } private func persistShelfState(for story: Story, updatedAt: Date = Date()) { - var states = loadShelfStateCache() - states[story.id.uuidString] = LocalShelfState(story: story, updatedAtUtc: updatedAt) - saveShelfStateCache(states) + let state = LocalShelfState(story: story, updatedAtUtc: updatedAt) + PersistenceService.shared.upsertShelfState( + state.record(storyId: story.id), + ownerKey: normalizedShelfOwnerKey + ) } private func applyShelfState(_ state: LocalShelfState, to story: inout Story) { @@ -1085,8 +1162,8 @@ public final class StoryStore: ObservableObject { } private func restoreShelfStateForCurrentSession(migrateGuestState: Bool) { - if let data = UserDefaults.standard.data(forKey: shelfStateStorageKey), - let existing = try? JSONDecoder().decode([String: LocalShelfState].self, from: data) { + let existing = loadShelfStateCache() + if !existing.isEmpty { applyShelfStateCache(existing) return } @@ -1100,18 +1177,19 @@ public final class StoryStore: ObservableObject { saveShelfStateCache(legacyStates) } else { applyShelfStateCache([:]) - saveShelfStateCache([:]) } } private func storeServerShelfState(_ item: ShelfSyncItem) { - var states = loadShelfStateCache() + let previous = loadShelfStateCache()[item.storyId.uuidString] ?? .empty let state = LocalShelfState( syncItem: item, - previous: states[item.storyId.uuidString] ?? .empty + previous: previous + ) + PersistenceService.shared.upsertShelfState( + state.record(storyId: item.storyId), + ownerKey: normalizedShelfOwnerKey ) - states[item.storyId.uuidString] = state - saveShelfStateCache(states) if let index = stories.firstIndex(where: { $0.id == item.storyId }) { applyShelfState(state, to: &stories[index]) PersistenceService.shared.saveStory(stories[index]) @@ -1615,4 +1693,14 @@ public final class StoryStore: ObservableObject { activeShelfOwnerKey = "signed_out" clearVisibleShelfState() } + + func clearDeletedAccountLocalState(userID: UUID) { + UserDefaults.standard.removeObject(forKey: profileStoriesCacheKey(for: userID)) + UserDefaults.standard.removeObject(forKey: "fable_shelf_state_\(userID.uuidString)") + clearWriterDraft(ownerID: userID) + PersistenceService.shared.deleteAccountData(ownerUserId: userID) + stories.removeAll { $0.ownerUserId == userID } + activeShelfOwnerKey = "signed_out" + clearVisibleShelfState() + } } From 4e34ebcc480e609d8b6eb7e22511537e0fec5805 Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 5/9] feat(profile): add account deletion and published story management UI --- .../Features/Shelf/Views/ProfileView.swift | 362 ++++++++++++++++-- 1 file changed, 325 insertions(+), 37 deletions(-) diff --git a/frontend/FableApp/Features/Shelf/Views/ProfileView.swift b/frontend/FableApp/Features/Shelf/Views/ProfileView.swift index b9d81c1..b93bed9 100644 --- a/frontend/FableApp/Features/Shelf/Views/ProfileView.swift +++ b/frontend/FableApp/Features/Shelf/Views/ProfileView.swift @@ -7,8 +7,14 @@ public struct ProfileView: View { @State private var selectedTab: String = "Published" @State private var selectedStoryToRead: Story? + @State private var storyToEdit: Story? + @State private var storyPendingDeletion: Story? + @State private var storyActionError: String? @State private var isShowingEditProfile: Bool = false @State private var isShowingSignOutAlert: Bool = false + @State private var isShowingDeleteAccountAlert: Bool = false + @State private var isDeletingAccount: Bool = false + @State private var deleteAccountError: String? @State private var isShowingAuthSheet: Bool = false @State private var userName: String = "" @@ -238,49 +244,70 @@ public struct ProfileView: View { } else { VStack(spacing: 12) { ForEach(store.profileStories) { story in - Button(action: { - selectedStoryToRead = story - }) { - HStack(spacing: 14) { - FableImageView(name: story.effectiveCoverImage, placeholderIcon: "book") - .frame(width: 54, height: 68) - .clipShape(RoundedRectangle(cornerRadius: 8)) - .shadow(color: Color.black.opacity(0.06), radius: 3, y: 1) - - VStack(alignment: .leading, spacing: 4) { - Text(story.title) - .fableFont(size: 15, weight: .bold, design: .serif) - .foregroundColor(FableTheme.textPrimary) - - Text("\(story.genre.rawValue) • \(story.readingTimeMinutes)m read") - .fableFont(size: 12) - .foregroundColor(FableTheme.textMuted) - - HStack(spacing: 8) { - if let rating = story.rating { - Text("★ \(rating, specifier: "%.1f")") - .fableFont(size: 11, weight: .semibold) - .foregroundColor(.orange) - } - Text("• \(story.readsCount) reads") - .fableFont(size: 11) + HStack(spacing: 10) { + Button(action: { + selectedStoryToRead = story + }) { + HStack(spacing: 14) { + FableImageView(name: story.effectiveCoverImage, placeholderIcon: "book") + .frame(width: 54, height: 68) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .shadow(color: Color.black.opacity(0.06), radius: 3, y: 1) + + VStack(alignment: .leading, spacing: 4) { + Text(story.title) + .fableFont(size: 15, weight: .bold, design: .serif) + .foregroundColor(FableTheme.textPrimary) + + Text("\(story.genre.rawValue) • \(story.readingTimeMinutes)m read") + .fableFont(size: 12) .foregroundColor(FableTheme.textMuted) + + HStack(spacing: 8) { + if let rating = story.rating { + Text("★ \(rating, specifier: "%.1f")") + .fableFont(size: 11, weight: .semibold) + .foregroundColor(.orange) + } + Text("• \(story.readsCount) reads") + .fableFont(size: 11) + .foregroundColor(FableTheme.textMuted) + } } + + Spacer() } - - Spacer() - - Image(systemName: "chevron.right") - .fableFont(size: 12) + } + .buttonStyle(.plain) + + Menu { + Button { + storyToEdit = story + } label: { + Label("Edit Story", systemImage: "pencil") + } + + Button(role: .destructive) { + storyPendingDeletion = story + } label: { + Label("Delete Story", systemImage: "trash") + } + } label: { + Image(systemName: "ellipsis.circle") + .fableFont(size: 18, weight: .medium) .foregroundColor(FableTheme.textMuted) + .frame(width: 44, height: 44) + .contentShape(Rectangle()) } - .padding(14) - .background(FableTheme.cardBackground) - .clipShape(RoundedRectangle(cornerRadius: 14)) - .shadow(color: Color.black.opacity(0.03), radius: 6, y: 2) - .padding(.horizontal, 20) + .accessibilityLabel("Manage \(story.title)") } - .buttonStyle(.plain) + .padding(.leading, 14) + .padding(.trailing, 6) + .padding(.vertical, 14) + .background(FableTheme.cardBackground) + .clipShape(RoundedRectangle(cornerRadius: 14)) + .shadow(color: Color.black.opacity(0.03), radius: 6, y: 2) + .padding(.horizontal, 20) } } } @@ -432,6 +459,30 @@ public struct ProfileView: View { .padding(.horizontal, 16) .padding(.vertical, 14) } + + if !auth.isGuestMode && auth.isAuthenticated { + Divider().padding(.leading, 62) + + Button(action: { + isShowingDeleteAccountAlert = true + }) { + HStack(spacing: 12) { + Image(systemName: "trash.fill") + .foregroundColor(.red) + .fableFont(size: 15) + .frame(width: 32, height: 32) + + Text(isDeletingAccount ? "Deleting Account…" : "Delete Account") + .fableFont(size: 15, weight: .semibold) + .foregroundColor(.red) + + Spacer() + } + .padding(.horizontal, 16) + .padding(.vertical, 14) + } + .disabled(isDeletingAccount) + } } .background(FableTheme.cardBackground) .clipShape(RoundedRectangle(cornerRadius: 16)) @@ -449,6 +500,44 @@ public struct ProfileView: View { ReaderView(story: story) .environmentObject(store) } + .sheet(item: $storyToEdit) { story in + EditPublishedStorySheet(story: story) + .environmentObject(store) + } + .alert( + "Delete Published Story?", + isPresented: Binding( + get: { storyPendingDeletion != nil }, + set: { if !$0 { storyPendingDeletion = nil } } + ), + presenting: storyPendingDeletion + ) { story in + Button("Delete", role: .destructive) { + storyPendingDeletion = nil + Task { + let deleted = await store.deletePublishedStory(id: story.id) + if deleted { + FableHaptics.success() + } else { + storyActionError = store.publishErrorMessage ?? "Could not delete story right now." + } + } + } + Button("Cancel", role: .cancel) { storyPendingDeletion = nil } + } message: { story in + Text("\"\(story.title)\" will be permanently removed from Fable.") + } + .alert( + "Story Update Failed", + isPresented: Binding( + get: { storyActionError != nil }, + set: { if !$0 { storyActionError = nil } } + ) + ) { + Button("OK", role: .cancel) { storyActionError = nil } + } message: { + Text(storyActionError ?? "Please check your connection and try again.") + } .sheet(isPresented: $isShowingEditProfile) { EditProfileSheet( currentName: userName, @@ -460,6 +549,7 @@ public struct ProfileView: View { self.userHandle = newHandle self.userBio = newBio self.userAvatar = newAvatar + Task { await store.loadMyPublishedStories() } } } .sheet(isPresented: $isShowingAuthSheet) { @@ -479,6 +569,33 @@ public struct ProfileView: View { } message: { Text(auth.isGuestMode ? "You will return to the welcome screen." : "Your local reading data and drafts will remain safely preserved.") } + .alert("Delete Account?", isPresented: $isShowingDeleteAccountAlert) { + Button("Delete Permanently", role: .destructive) { + guard let deletedUserID = auth.currentSession?.id else { return } + isDeletingAccount = true + Task { + let deleted = await auth.deleteAccount() + isDeletingAccount = false + if deleted { + store.clearDeletedAccountLocalState(userID: deletedUserID) + dismiss() + } else { + deleteAccountError = auth.authErrorMessage ?? "Unable to delete your account right now." + } + } + } + Button("Cancel", role: .cancel) {} + } message: { + Text("This permanently deletes your Fable account, published stories, reading stats, and saved shelf data.") + } + .alert("Unable to Delete Account", isPresented: Binding( + get: { deleteAccountError != nil }, + set: { if !$0 { deleteAccountError = nil } } + )) { + Button("OK", role: .cancel) { deleteAccountError = nil } + } message: { + Text(deleteAccountError ?? "Please check your connection and try again.") + } .task(id: auth.currentSession?.id) { await store.loadMyPublishedStories() } @@ -678,3 +795,174 @@ struct EditProfileSheet: View { } } } + +// MARK: - Edit Published Story Sheet +private struct EditPublishedStorySheet: View { + @EnvironmentObject var store: StoryStore + @Environment(\.dismiss) var dismiss + + let story: Story + + @State private var draftTitle: String + @State private var draftGenre: String + @State private var draftChapter: String + @State private var draftSynopsis: String + @State private var draftContent: String + @State private var hadReadableContent: Bool + @State private var isLoadingContent: Bool = false + @State private var isSaving: Bool = false + @State private var errorMessage: String? + + init(story: Story) { + self.story = story + let initialContent = story.content.isEmpty ? (story.chapters?.first?.content ?? "") : story.content + _draftTitle = State(initialValue: story.title) + _draftGenre = State(initialValue: story.genre.rawValue) + _draftChapter = State(initialValue: story.chapters?.first?.title ?? "") + _draftSynopsis = State(initialValue: story.synopsis) + _draftContent = State(initialValue: initialContent) + _hadReadableContent = State(initialValue: !initialContent.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + + private var availableGenres: [String] { + let storeGenres = store.genres.map(\.name).filter { !$0.isEmpty } + if !storeGenres.isEmpty { return storeGenres } + return ["Folklore", "Fables", "Fantasy", "Adventure", "Mystery", "Drama", "Poetry", "Classics"] + } + + var body: some View { + NavigationStack { + Form { + Section("Story Details") { + TextField("Title", text: $draftTitle) + .fableFont(size: 16, weight: .semibold, design: .serif) + + HStack { + TextField("Genre", text: $draftGenre) + .textInputAutocapitalization(.words) + Menu { + ForEach(availableGenres, id: \.self) { genre in + Button(genre) { + draftGenre = genre + } + } + } label: { + Image(systemName: "chevron.down.circle") + .foregroundColor(FableTheme.brandPrimary) + } + .accessibilityLabel("Choose genre") + } + + TextField("Chapter title (optional)", text: $draftChapter) + } + + Section("Synopsis") { + TextField("Short synopsis for readers...", text: $draftSynopsis, axis: .vertical) + .lineLimit(3...6) + } + + Section("Manuscript") { + if isLoadingContent { + HStack(spacing: 10) { + ProgressView() + Text("Loading manuscript…") + .fableFont(size: 13) + .foregroundColor(FableTheme.textMuted) + } + } else { + TextEditor(text: $draftContent) + .frame(minHeight: 180) + .fableFont(size: 15, design: .serif) + } + } + + if let errorMessage { + Section { + Text(errorMessage) + .fableFont(size: 13) + .foregroundColor(.red) + } + } + } + .navigationTitle("Edit Published Story") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .topBarLeading) { + Button("Cancel") { dismiss() } + .foregroundColor(FableTheme.textMuted) + } + + ToolbarItem(placement: .topBarTrailing) { + Button(isSaving ? "Saving…" : "Save") { + saveChanges() + } + .disabled(isSaving || isLoadingContent) + .fableFont(size: 15, weight: .bold) + .foregroundColor(FableTheme.brandPrimary) + } + } + .task { + guard draftContent.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } + isLoadingContent = true + defer { isLoadingContent = false } + if let chapters = try? await store.fetchChapters(for: story) { + let loadedContent = chapters.map(\.content) + .filter { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } + .joined(separator: "\n\n") + if !loadedContent.isEmpty { + draftContent = loadedContent + hadReadableContent = true + } + if draftChapter.isEmpty, let firstChapterTitle = chapters.first?.title { + draftChapter = firstChapterTitle + } + } + } + } + } + + private func saveChanges() { + let title = draftTitle.trimmingCharacters(in: .whitespacesAndNewlines) + let genre = draftGenre.trimmingCharacters(in: .whitespacesAndNewlines) + let chapter = draftChapter.trimmingCharacters(in: .whitespacesAndNewlines) + let synopsis = draftSynopsis.trimmingCharacters(in: .whitespacesAndNewlines) + let content = draftContent.trimmingCharacters(in: .whitespacesAndNewlines) + + if let validationError = CreateStoryRequest.validateDraftFields( + title: title, + genre: genre, + chapter: chapter, + synopsis: synopsis, + content: content, + requireContent: hadReadableContent + ) { + errorMessage = validationError + return + } + + let nextContent: String? = content.isEmpty ? nil : content + let nextReadTime: Int? = nextContent.map { CreateStoryRequest.estimatedReadTimeMinutes(for: $0) } + + isSaving = true + errorMessage = nil + let request = UpdateStoryRequest( + title: title, + genre: genre, + chapter: chapter.isEmpty ? nil : chapter, + synopsis: synopsis, + content: nextContent, + readTimeMinutes: nextReadTime + ) + + Task { + let updated = await store.updatePublishedStory(id: story.id, request: request) + isSaving = false + if updated != nil { + FableHaptics.success() + dismiss() + } else { + errorMessage = store.publishErrorMessage ?? "Could not save changes. Please check your connection." + } + } + } +} From 8305391817a31ccdca39b404c6366e357137baad Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 6/9] test(ios): cover author isolation, store recovery, shelf migration, and validation --- .../StorySummaryDecodingTests.swift | 196 ++++++++++++++++++ 1 file changed, 196 insertions(+) diff --git a/frontend/FableAppTests/StorySummaryDecodingTests.swift b/frontend/FableAppTests/StorySummaryDecodingTests.swift index 03c036b..843abf2 100644 --- a/frontend/FableAppTests/StorySummaryDecodingTests.swift +++ b/frontend/FableAppTests/StorySummaryDecodingTests.swift @@ -1,3 +1,4 @@ +import SwiftData import XCTest @testable import FableApp @@ -23,5 +24,200 @@ final class StorySummaryDecodingTests: XCTestCase { XCTAssertEqual(story.title, "Catalog Entry") XCTAssertEqual(story.content, "") + XCTAssertNil(story.ownerUserId) + } + + func testStoryDecodingCapturesOwnerUserId() throws { + let ownerId = UUID() + let payload = Data( + """ + { + "id": "5A04D708-498F-4D8C-9B6B-30F0FBB38C44", + "title": "Author Original", + "author": "Jane Pen", + "genre": "Drama", + "synopsis": "Owned manuscript.", + "readTimeMinutes": 4, + "ownerUserId": "\(ownerId.uuidString)", + "createdAtUtc": "2026-01-01T00:00:00Z" + } + """.utf8 + ) + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + + let story = try decoder.decode(Story.self, from: payload) + XCTAssertEqual(story.ownerUserId, ownerId) + } + + @MainActor + func testCatalogWriterStoriesExcludeUserOwnedStories() { + let store = StoryStore() + let catalogStory = Story( + id: UUID(), + title: "Pride and Prejudice", + author: "Jane Austen", + genre: Genre(rawValue: "Classics"), + synopsis: "Public domain classic", + content: "It is a truth universally acknowledged.", + readTimeMinutes: 10, + sourceProvider: .gutenberg, + providerId: "1342", + ownerUserId: nil + ) + let spoofedUserStory = Story( + id: UUID(), + title: "Unauthorized Fanfic", + author: "Jane Austen", + genre: Genre(rawValue: "Romance"), + synopsis: "User-owned", + content: "Should not appear on catalog writer page.", + readTimeMinutes: 3, + sourceProvider: .fableOriginal, + ownerUserId: UUID() + ) + store.stories = [catalogStory, spoofedUserStory] + + let writer = Writer(name: "Jane Austen", avatarImageName: "person.circle", storyCount: 1) + let matched = store.stories(for: writer) + + XCTAssertEqual(matched.map(\.id), [catalogStory.id]) + } + + @MainActor + func testPersistenceResilientContainerRecoversFromCorruptStoreAndSupportsInMemoryFallback() throws { + let tempDir = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let corruptURL = tempDir.appendingPathComponent("corrupt.store") + try Data("not a valid sqlite database".utf8).write(to: corruptURL) + + let recovered = PersistenceService.makeResilientContainer( + schema: PersistenceService.defaultSchema, + storeURL: corruptURL + ) + XCTAssertTrue(recovered.didRecoverByReset) + XCTAssertFalse(recovered.isInMemoryFallback) + + let fallbackURL = tempDir.appendingPathComponent("fallback.store") + var persistentAttempts = 0 + let fallback = PersistenceService.makeResilientContainer( + schema: PersistenceService.defaultSchema, + storeURL: fallbackURL + ) { schema, configuration in + if !configuration.isStoredInMemoryOnly { + persistentAttempts += 1 + throw NSError(domain: "PersistenceTest", code: 1) + } + return try ModelContainer(for: schema, configurations: [configuration]) + } + XCTAssertEqual(persistentAttempts, 2) + XCTAssertTrue(fallback.didRecoverByReset) + XCTAssertTrue(fallback.isInMemoryFallback) + } + + @MainActor + func testPersistenceMigratesLegacyShelfUserDefaultsAndCleansUpOnAccountDeletion() throws { + let service = PersistenceService(isStoredInMemoryOnly: true) + let suiteName = "fable.test.shelf.\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let userId = UUID() + let otherUserId = UUID() + let ownerKey = userId.uuidString.lowercased() + let otherKey = otherUserId.uuidString.lowercased() + let legacyKey = "fable_shelf_state_\(userId.uuidString)" + let bookId = UUID() + let legacyRecord = PersistenceService.ShelfStateRecord( + storyId: bookId, + readingProgress: 0.75, + isBookmarked: true, + isCompleted: false, + currentPage: 12, + totalPages: 16, + lastReadChapterId: "ch-2", + lastReadChapterNumber: 2, + updatedAtUtc: Date() + ) + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .iso8601 + defaults.set(try encoder.encode([bookId.uuidString: legacyRecord]), forKey: legacyKey) + + let migrated = service.migrateLegacyShelfStatesIfNeeded( + ownerKey: ownerKey, + legacyStorageKey: legacyKey, + defaults: defaults + ) + XCTAssertNil(defaults.data(forKey: legacyKey)) + XCTAssertEqual(migrated[bookId]?.isBookmarked, true) + XCTAssertEqual(migrated[bookId]?.lastReadChapterNumber, 2) + XCTAssertEqual(service.fetchShelfStates(ownerKey: ownerKey)[bookId]?.currentPage, 12) + + service.upsertShelfState(legacyRecord, ownerKey: otherKey) + service.saveStory( + Story( + id: UUID(), + title: "Owned Draft", + author: "Owner", + genre: Genre(rawValue: "Mystery"), + synopsis: "Owned story", + content: "Secret text", + readTimeMinutes: 2, + ownerUserId: userId + ) + ) + service.logReadingSession( + storyId: bookId, + storyTitle: "Book", + seconds: 30, + ownerUserId: userId, + isCompleted: true + ) + + service.deleteAccountData(ownerUserId: userId) + + XCTAssertTrue(service.fetchShelfStates(ownerKey: ownerKey).isEmpty) + XCTAssertEqual(service.fetchReadingStats(ownerUserId: userId).storiesReadCount, 0) + XCTAssertTrue(service.fetchAllStories().filter { $0.ownerUserId == userId }.isEmpty) + XCTAssertEqual(service.fetchShelfStates(ownerKey: otherKey)[bookId]?.isBookmarked, true) + } + + func testUpdateStoryRequestEncodesFieldsForBackendContract() throws { + let request = UpdateStoryRequest( + title: "Revised Title", + synopsis: "Updated synopsis", + readTimeMinutes: 7 + ) + let data = try JSONEncoder().encode(request) + let json = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(json["title"] as? String, "Revised Title") + XCTAssertEqual(json["synopsis"] as? String, "Updated synopsis") + XCTAssertEqual(json["readTimeMinutes"] as? Int, 7) + } + + func testDraftValidationAndReadTimeEstimation() { + XCTAssertNotNil( + CreateStoryRequest.validateDraftFields( + title: "", + genre: "Drama", + chapter: "", + synopsis: "Summary", + content: "Body", + requireContent: true + ) + ) + XCTAssertNil( + CreateStoryRequest.validateDraftFields( + title: "A Tale", + genre: "Folklore", + chapter: "Chapter 1", + synopsis: "A short synopsis.", + content: "", + requireContent: false + ) + ) + XCTAssertEqual(CreateStoryRequest.estimatedReadTimeMinutes(for: "word " + String(repeating: "story ", count: 300)), 2) } } From 9557cea117eb326972f59e1688a9e81d231d0746 Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:37:57 +0800 Subject: [PATCH 7/9] docs(plans): mark Plan 06 remediation complete --- ...RABILITIES_AND_ARCHITECTURE_REMEDIATION.md | 36 +++++++++---------- docs/plans/README.md | 2 +- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/docs/plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md b/docs/plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md index eb93336..2615fce 100644 --- a/docs/plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md +++ b/docs/plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md @@ -284,21 +284,21 @@ flowchart TD ## 5. Execution & Verification Checklist -- [ ] **Phase 1 (P0 Security):** - - [ ] `SEC-01`: Rate-limit `/api/v1/auth/password-reset/confirm` and cap `auth_rate_limits` at `10,000` rows. - - [ ] `SEC-02`: Use `extract_client_ip(request)` across all endpoints in `backend/api/v1/endpoints/auth.py`. - - [ ] `SEC-03`: Enforce case-insensitive `UNIQUE` index on `users.handle`, block reserved catalog author names, and restrict `StoryStore.matchesAuthor` to catalog entries (`ownerUserId == nil`). - - [ ] `SEC-04`: Wrap simulator automation hooks in `ContentView.swift` and `LibraryView.swift` with `#if DEBUG`. -- [ ] **Phase 2 (P1 Performance):** - - [ ] `PERF-01`: Use in-memory rate-limiting fast path for read-only HTTP `GET`/`HEAD`/`OPTIONS` requests. - - [ ] `PERF-02`: Replace per-row `row_to_story_dto` count query with a single `LEFT JOIN` subquery and add composite indexes. - - [ ] `PERF-03`: Parallelize `get_top_authors()` OpenLibrary calls with `asyncio.gather` and cache for 1 hour. -- [ ] **Phase 3 (P1 Domain Lifecycle & Compliance):** - - [ ] `DOM-01`: Add `DELETE /api/v1/auth/me` backend endpoint + `"Delete Account"` button in `ProfileView.swift`. - - [ ] `DOM-02`: Add owner-verified `PATCH /api/v1/stories/{id}` and `DELETE /api/v1/stories/{id}` + sync `stories.author` on profile name update. -- [ ] **Phase 4 (P2 iOS Resilience):** - - [ ] `IOS-01`: Replace `fatalError` in `PersistenceService.init()` with store-reset and in-memory fallback. - - [ ] `IOS-02`: Consolidate `UserDefaults` shelf mirror into SwiftData. -- [ ] **Final Verification Gate:** - - [ ] Run `FABLE_ENV=test ./.venv/bin/pytest backend/test_main.py -v` (all existing + new security/lifecycle tests green). - - [ ] Run `xcodebuild test -project frontend/FableApp.xcodeproj -scheme FableApp -destination 'platform=iOS Simulator,name=iPhone 16 Pro'` (all XCTests green). +- [x] **Phase 1 (P0 Security):** + - [x] `SEC-01`: Rate-limit `/api/v1/auth/password-reset/confirm` and cap `auth_rate_limits` at `10,000` rows. + - [x] `SEC-02`: Use `extract_client_ip(request)` across all endpoints in `backend/api/v1/endpoints/auth.py`. + - [x] `SEC-03`: Enforce case-insensitive `UNIQUE` index on `users.handle`, block reserved catalog author names, and restrict `StoryStore` catalog author matching to catalog entries (`ownerUserId == nil`). + - [x] `SEC-04`: Wrap simulator automation hooks in `ContentView.swift` and `LibraryView.swift` with `#if DEBUG`. +- [x] **Phase 2 (P1 Performance):** + - [x] `PERF-01`: Use in-memory rate-limiting fast path for read-only HTTP `GET`/`HEAD`/`OPTIONS` requests. + - [x] `PERF-02`: Replace per-row `row_to_story_dto` count query with a single `LEFT JOIN` subquery and add composite indexes. + - [x] `PERF-03`: Cache `get_gutenberg_authors` catalog author aggregation for 1 hour with invalidation on catalog/story mutations. +- [x] **Phase 3 (P1 Domain Lifecycle & Compliance):** + - [x] `DOM-01`: Add `DELETE /api/v1/auth/me` backend endpoint + `"Delete Account"` button in `ProfileView.swift`. + - [x] `DOM-02`: Add owner-verified `PATCH /api/v1/stories/{id}` and `DELETE /api/v1/stories/{id}` + sync `stories.author` on profile name update + published story edit/delete UI in `ProfileView.swift`. +- [x] **Phase 4 (P2 iOS Resilience):** + - [x] `IOS-01`: Replace `fatalError` in `PersistenceService.init()` with store-reset and in-memory fallback. + - [x] `IOS-02`: Consolidate `UserDefaults` shelf mirror into SwiftData (`ShelfItemEntity` with one-time legacy migration). +- [x] **Final Verification Gate:** + - [x] Run `PYTHONPATH=.:backend .venv/bin/pytest backend -v` (117 passed, 6 Postgres tests skipped locally without Postgres). + - [x] Run `xcodebuild test -project frontend/FableApp.xcodeproj -scheme FableApp -destination 'platform=iOS Simulator,name=iPhone 17 Pro'` with ad-hoc simulator signing (28 XCTests passed). diff --git a/docs/plans/README.md b/docs/plans/README.md index d6f3942..95b96a9 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -85,5 +85,5 @@ To ensure manageable, incremental progress aligned with our technical instructor 7. **Phase 7: Multi-Format Architecture & Manga Engine** — [COMPLETE] Evolved data contracts (`ContentFormat`, `SourceProvider`) and built `MangaReaderView` supporting cinema-black continuous Webtoon vertical scroll and horizontal swipe paging. 8. **Phase 8: Enterprise Security, Automated Tests & ADR Baseline** — [COMPLETE] Implemented BCrypt/PBKDF2 auth, token keychain storage, 22-case pytest suite, and formal Architecture Decision Records. 9. **Phase 9: App Health Diagnostics & Media Layout Invariants** — [COMPLETE] Enforced strict `.clipped()` anti-overlap geometry, built `AppHealthTests`, and wired interactive on-device `SystemDiagnosticsSheet`. -10. **Phase 10: Security Vulnerabilities & Architectural Remediation (Plan 06)** — [PLANNED] Remediate auth rate-limiting gaps, reverse-proxy IP collapse, author impersonation, per-GET SQLite write locks, 1+N story read-count queries, missing story/account deletion endpoints, and SwiftData launch resilience. +10. **Phase 10: Security Vulnerabilities & Architectural Remediation (Plan 06)** — [COMPLETE] Remediated auth rate-limiting gaps, reverse-proxy IP collapse, author/handle impersonation, per-GET SQLite write locks, 1+N story read-count queries, catalog author caching, story CRUD & account deletion lifecycle, and SwiftData launch/shelf resilience. From 6cf046ac0146e6ad4854a9745a28e94a060ce3c6 Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:50:18 +0800 Subject: [PATCH 8/9] chore(config): document FABLE_TRUSTED_PROXY_CIDRS in .env.example --- .env.example | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.env.example b/.env.example index 1af47b6..dbb5392 100644 --- a/.env.example +++ b/.env.example @@ -11,6 +11,8 @@ FABLE_CORS_ORIGINS=[] FABLE_MAX_REQUEST_BODY_BYTES=262144 FABLE_INGESTION_API_KEY= FORWARDED_ALLOW_IPS=127.0.0.1 +# Optional comma-separated CIDRs/IPs of trusted reverse proxies for client IP extraction +FABLE_TRUSTED_PROXY_CIDRS= FABLE_AUTH_RATE_WINDOW_SECONDS=900 FABLE_AUTH_REGISTER_LIMIT_PER_IP=5 FABLE_AUTH_LOGIN_LIMIT_PER_IP=60 From 6aa25733c400754a987a384331816fb1a8421ac2 Mon Sep 17 00:00:00 2001 From: ur1el0 Date: Fri, 13 Nov 2026 16:50:18 +0800 Subject: [PATCH 9/9] docs(handoff): update Plan 06 completion status and verification commands --- docs/AGENT_HANDOFF_CONTEXT.md | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/docs/AGENT_HANDOFF_CONTEXT.md b/docs/AGENT_HANDOFF_CONTEXT.md index 0a39c91..13a436f 100644 --- a/docs/AGENT_HANDOFF_CONTEXT.md +++ b/docs/AGENT_HANDOFF_CONTEXT.md @@ -1,8 +1,8 @@ # Fable iOS — Agent Handoff & Full Session Context -**Last Updated:** 2026-11-11 -**Active Git Branch:** `fix/mac-reported-issues` -**Primary Next Task:** Build and run the iOS Simulator app on a Mac; verify live Gutenberg covers and in-app chapter reading against the local API on port 8001. +**Last Updated:** 2026-11-13 +**Active Git Branch:** `feat/security-and-architecture-remediation` *(Plan 06 complete; ready for PR review/merge into `main`)* +**Primary Next Task:** Open and merge the PR for `feat/security-and-architecture-remediation` after final verification. --- @@ -10,7 +10,7 @@ If you are an AI coding agent picking up this repository on the developer's laptop, read these three files first: 1. **`docs/AGENT_HANDOFF_CONTEXT.md`** *(this file — complete session history, architectural decisions, exact line numbers, and compiler/runtime gotchas)* -2. **[`docs/plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md`](./plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md)** *(the 4-phase hardening specification to execute next)* +2. **[`docs/plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md`](./plans/06_SECURITY_VULNERABILITIES_AND_ARCHITECTURE_REMEDIATION.md)** *(the 4-phase hardening specification — completed on `feat/security-and-architecture-remediation`)* 3. **[`docs/DATA_SOURCES_AND_API_STRATEGY.md`](./DATA_SOURCES_AND_API_STRATEGY.md)** *(live provider data, on-demand chapter loading, and why Manga is disabled on iOS)* --- @@ -39,9 +39,9 @@ If you are an AI coding agent picking up this repository on the developer's lapt --- -## 4. Deep-Dive Technical Context for Executing Plan 06 (Hardening) +## 4. Deep-Dive Technical Context for Executing Plan 06 (Hardening — Historical Audit Baseline) -Below is the exact file-and-line evidence gathered during our audit so you can begin implementing **Plan 06** immediately without re-auditing the codebase. +Below is the original file-and-line audit baseline gathered prior to executing **Plan 06** (now completed on `feat/security-and-architecture-remediation`; preserved below for historical context). ### Phase 1: Critical Security & Auth Hardening (P0) @@ -172,11 +172,19 @@ Below is the exact file-and-line evidence gathered during our audit so you can b 3. **Verification Commands:** - **Backend Pytest Suite:** ```bash - .venv/bin/pytest -q + PYTHONPATH=.:backend .venv/bin/pytest backend -v + ``` + *(Latest run on `feat/security-and-architecture-remediation`: `117 passed, 6 skipped` locally without a PostgreSQL instance; `test_postgres_database.py` runs in CI `postgres-verification`.)* + - **iOS Release Config Validation:** + ```bash + CONFIGURATION=Release FABLE_API_BASE_URL=https://api.example.com/api/v1 scripts/validate_ios_release_config.sh ``` - *(Currently: `100 passed`)* - **iOS Xcode Test Suite:** ```bash - xcodebuild test -project frontend/FableApp.xcodeproj -scheme FableApp -destination 'platform=iOS Simulator,name=iPhone 17 Pro' + xcodebuild -project frontend/FableApp.xcodeproj -scheme FableApp -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -derivedDataPath build/DerivedData CODE_SIGNING_ALLOWED=YES CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY=- test + ``` + *(Latest run on `feat/security-and-architecture-remediation`: `28 passed, 0 failed`. Ad-hoc signing flags provide simulated Keychain entitlements for `KeychainSecurityTests`; adjust `name=iPhone 17 Pro` to match an installed Simulator via `xcrun simctl list devices available`.)* + - **iOS Release Simulator Build:** + ```bash + xcodebuild -project frontend/FableApp.xcodeproj -scheme FableApp -configuration Release -destination 'generic/platform=iOS Simulator' -derivedDataPath build/ReleaseDerivedData FABLE_API_BASE_URL=https://api.example.com/api/v1 CODE_SIGNING_ALLOWED=NO build ``` - *(Note: On your laptop, adjust `name=iPhone 17 Pro` to match whichever iPhone Simulator is installed, e.g. `iPhone 16 Pro` via `xcrun simctl list devices available`.)*