"""Etsy offline clone - persistent backend (stage: backend, R3). FastAPI + Jinja2 frontend over a stdlib-sqlite3 WAL database (clone/backend/db.py). Sessions, cart lines, and favorites are persisted across restarts; all catalog data is served from deterministic seeded rows. Fidelity-first, decoupled from tasks: the backend accepts ANY valid variation tuple for a listing's configured axes and ANY personalization text within a listing's configured character limit. No benchmark task constant is validated for or branched on anywhere in this module. Server-authoritative pricing: unit prices are computed only from the database (per-combination grid or base + option deltas); client-posted price fields are never read. Cart lines are opaque server-owned rows addressed by server-generated tokens. Duplicate-add policy (documented in backend/db.py, applied generically): adding an identical (listing, full variation tuple, personalization) line merges by summing quantities, capped by the per-listing maximum. """ from __future__ import annotations import hashlib import hmac import json import os import sys import threading import uuid from datetime import datetime from decimal import Decimal from pathlib import Path from urllib.parse import parse_qs, quote import uvicorn from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates _CLONE_DIR = str(Path(__file__).resolve().parent) if _CLONE_DIR not in sys.path: sys.path.insert(0, _CLONE_DIR) from backend import db, purchases # noqa: E402 from backend.site_backend_integration import open_site_services # noqa: E402 from websitebench.local_clone_auth import ( # noqa: E402 AuthConflict, AuthError, AuthRateLimited, AuthValidationError, LocalAuthStore, MAIL_SMTP_PENDING, RESET_PUBLIC_MESSAGE, ) from websitebench.public_clone_auth import ( # noqa: E402 VerificationUnavailable, load_public_clone_registration_verification, ) from websitebench.public_clone_auth.fastapi import ( # noqa: E402 consume_registration_ticket, registration_script_response, send_registration_code, verify_registration_code, ) from websitebench.site_backend.stripe_test import ( # noqa: E402 StripeTestError, StripeTestGateway, StripeTestLineItem, StripeTestUnavailable, ) SITE_ID = "etsy" PUBLIC_REGISTRATION_VERIFICATION = load_public_clone_registration_verification() VERSION = "etsy-fullstack-2026-08-11.1" FIXTURE_ID = "etsy-v3-fullstack-candidate" FROZEN_CLOCK = db.FROZEN_CLOCK STAGE = "fullstack-candidate" SESSION_COOKIE = "clawbench_etsy_sid" CSRF_VALUE = "etsy-form-2026-07-29" DEFAULT_ADMIN_TOKEN = "etsy-admin-dev-token" ADMIN_TOKEN_HEADER = "X-Clawbench-Admin-Token" ADMIN_SITE_HEADER = "X-Clawbench-Site-Id" ADMIN_SCHEMA_HEADER = "X-Clawbench-Schema-Head" ADMIN_SEED_HEADER = "X-Clawbench-Seed-Version" SEED_VERSION = "etsy-seed-2026-07-25" SEED_AUTH_ACCOUNTS = { "alex": { "email": "alex.green@example.test", "display_name": "Alex Green", "password": "Etsy-Alex-2026!", }, "jordan": { "email": "jordan.lee@example.test", "display_name": "Jordan Lee", "password": "Etsy-Jordan-2026!", }, } ROOT = Path(__file__).resolve().parent templates = Jinja2Templates(directory=str(ROOT / "frontend" / "templates")) templates.env.globals["public_registration_enabled"] = ( PUBLIC_REGISTRATION_VERIFICATION is not None ) # Search-page presentation metadata (captured page facts, not task logic). PAGE_CHIPS = { "search-personalized-wallet": ["Personalizable"], "search-dog-collar": ["Personalizable"], "search-blue-vase": ["Exclude digital downloads"], "search-bookshelf": ["Exclude digital downloads"], } PRICE_FILTERABLE_PAGES = {"search-blue-vase", "search-bookshelf"} TOP_NAVIGATION = [ ("🎁 Gifts", "/featured/hub/gifts"), ("Back-to-School Picks", "/r/curated/back-to-school-picks"), ("Home Favorites", "/featured/hub/home-favorites"), ("Fashion Finds", "/featured/hub/fashion-favorites"), ("Vintage", "/r/curated/etsys-best-vintage-finds"), ("Registry", "/registry"), ("Gift Cards", "/giftcards"), ] CATEGORY_MENU = [ ("Accessories", "accessories"), ("Art & Collectibles", "art-and-collectibles"), ("Bags & Purses", "bags-and-purses"), ("Bath & Beauty", "bath-and-beauty"), ("Books, Movies & Music", "books-movies-and-music"), ("Clothing", "clothing"), ("Craft Supplies & Tools", "craft-supplies-and-tools"), ("Electronics & Accessories", "electronics-and-accessories"), ("Gifts", "gifts"), ("Home & Living", "home-and-living"), ("Jewelry", "jewelry"), ("Kids & Baby", "kids-and-baby"), ("Paper & Party Supplies", "paper-and-party-supplies"), ("Pet Supplies", "pet-supplies"), ("Shoes", "shoes"), ("Toys & Games", "toys-and-games"), ("Weddings", "weddings"), ] CATEGORY_DETAILS = { "home-and-living": { "title": "Home & Living", "description": ( "Kitchen and dining, storage solutions, rugs, lighting, wall decor, " "and furniture—everything you need to make your home yours" ), "subcategories": [ ("Home Decor", "home-decor", "home-category-11.jpg"), ("Floor & Rugs", "floor-and-rugs", "home-category-12.jpg"), ("Furniture", "furniture", "home-category-13.jpg"), ("Outdoor & Gardening", "outdoor-and-gardening", "home-category-14.jpg"), ("Lighting", "lighting", "home-category-15.jpg"), ("Bathroom", "bathroom", "home-category-16.jpg"), ], }, "gifts": { "title": "Gifts", "description": "Thoughtful finds for every person, milestone, and celebration.", }, "back-to-school-picks": { "title": "Back-to-School Picks", "description": "Personalized supplies, dorm details, and one-of-a-kind school-day finds.", }, "home-favorites": { "title": "Home Favorites", "description": "Fresh decor, furniture, and handmade accents for every room.", }, "fashion-favorites": { "title": "Fashion Finds", "description": "Independent style, accessories, and personalized pieces.", }, "etsys-best-vintage-finds": { "title": "Vintage", "description": "Distinctive pieces with a story, selected from independent shops.", }, "registry": { "title": "Etsy Registry", "description": "Collect meaningful handmade, personalized, and vintage gifts in one place.", }, "giftcards": { "title": "Etsy Gift Cards", "description": "Give someone the freedom to find something made just for them.", }, } DEFAULT_SUBCATEGORIES = [ ("Personalized Finds", "personalized-finds", "home-category-11.jpg"), ("Handmade Style", "handmade-style", "home-category-12.jpg"), ("New Favorites", "new-favorites", "home-category-13.jpg"), ("Vintage Finds", "vintage-finds", "home-category-14.jpg"), ("Creative Gifts", "creative-gifts", "home-category-15.jpg"), ("Shop Essentials", "shop-essentials", "home-category-16.jpg"), ] INFO_PAGES = { "gift-cards": ("Gift cards", "Choose a gift card and let them find the perfect piece."), "sitemap": ("Sitemap", "Browse popular Etsy departments and shopping destinations."), "etsy-blog": ("Etsy blog", "Meet makers and discover fresh shopping inspiration."), "sell-on-etsy": ("Sell on Etsy", "Learn how independent sellers open and grow a shop."), "teams": ("Teams", "Connect with creative communities and other Etsy sellers."), "forums": ("Forums", "Explore conversations from the seller community."), "affiliates-and-creators": ("Affiliates & Creators", "Discover ways to share Etsy finds."), "etsy-inc": ("Etsy, Inc.", "Learn more about Etsy and its marketplace."), "policies": ("Policies", "Read marketplace, purchase, and seller policies."), "investors": ("Investors", "Company information for the investor community."), "careers": ("Careers", "Explore opportunities to help keep commerce human."), "press": ("Press", "Company news and media resources."), "impact": ("Impact", "See how Etsy works toward positive economic and environmental impact."), "privacy": ("Privacy", "Review privacy choices and information practices."), "terms": ("Terms of Use", "Review the terms that apply when using this marketplace."), "interest-based-ads": ("Interest-based ads", "Learn about advertising and privacy controls."), "local-shops": ("Local Shops", "Discover independent sellers near you."), "regions": ("Regions", "Choose a country, language, and currency."), "accessibility": ("Accessibility", "Find information about accessible shopping experiences."), "mobile-apps": ("Etsy apps", "Shop and manage favorites from Etsy mobile apps."), } COMPANY_NAVIGATION = [ ("About", "/about", "about"), ("Team", "/team", "team"), ("Careers", "/careers", "careers"), ("Press", "/press", "press"), ("Impact", "/impact", "impact"), ("Investors", "/investors", "investors"), ] COMPANY_PAGES = { "about": { "heading": "Keep Commerce Human", "lead": ( "Etsy is the global marketplace for unique and creative goods, " "from handcrafted pieces to vintage treasures." ), "body": [ ( "In a time of increasing automation, our mission is to keep human " "connection at the heart of commerce. Creativity thrives here because " "the marketplace is powered by people." ), ( "Our community of sellers turns ideas into businesses and connects with " "buyers looking for something personal, imaginative, and made with care." ), ], "section_heading": "How Etsy Works", "section_lead": ( "Real people connect over special goods while Etsy provides the tools and " "support that help those exchanges happen." ), "cards": [ ("Sell extraordinarily", "Creative entrepreneurs can start, manage, and grow their shops.", "/info/sell-on-etsy", "Become a seller"), ("Buy extraordinary", "Search and curated collections help shoppers find one-of-a-kind pieces.", "/c/gifts", "Start shopping"), ("Shop securely", "Account, order, and marketplace help are available when you need them.", "/help", "Get help"), ], }, "team": { "heading": "Meet the people behind Etsy", "lead": "Our teams build the marketplace and support the creative community that brings it to life.", "body": ["We bring together product, engineering, design, operations, and marketplace expertise.", "Across every discipline, the goal is the same: make commerce feel more human."], "section_heading": "How we work together", "section_lead": "Thoughtful collaboration keeps buyers, sellers, and the wider community at the center.", "cards": [ ("Build for people", "We start with the real needs of buyers and sellers.", "/impact", "See our impact"), ("Create with care", "We pair experimentation with responsibility and craft.", "/about", "Our mission"), ("Grow together", "Different perspectives help the marketplace improve.", "/careers", "Explore careers"), ], }, "careers": { "heading": "Come work with us", "lead": "Help build products and programs that keep creativity and human connection at the heart of commerce.", "body": ["Etsy teams solve meaningful problems across product, technology, operations, and community.", "We value curiosity, thoughtful decisions, and work that creates lasting impact."], "section_heading": "Find your place", "section_lead": "Learn about our teams, values, and the work behind the marketplace.", "cards": [ ("Our teams", "Meet the disciplines that build and support Etsy.", "/team", "Meet the team"), ("Our impact", "See the goals that guide how we grow.", "/impact", "View impact"), ("Company news", "Follow product and company updates.", "/press", "Visit press"), ], }, "press": { "heading": "Etsy news and press", "lead": "Company updates, marketplace stories, and resources about Etsy and its community.", "body": ["Discover recent developments across the marketplace and the people who power it.", "Press resources provide background on Etsy's mission, teams, and impact."], "section_heading": "Company resources", "section_lead": "Explore the story and principles behind Etsy.", "cards": [ ("About Etsy", "Learn why our mission is to keep commerce human.", "/about", "Read our story"), ("Impact", "Explore economic, social, and environmental progress.", "/impact", "See our impact"), ("Investors", "Review company and marketplace information.", "/investors", "Investor overview"), ], }, "impact": { "heading": "Making a positive impact", "lead": "We aim to create economic opportunity while supporting people, communities, and the planet.", "body": ["Our marketplace helps creative entrepreneurs reach buyers around the world.", "We measure progress and keep improving how our work affects the communities we serve."], "section_heading": "What guides us", "section_lead": "Impact is part of how we design products, support sellers, and operate the marketplace.", "cards": [ ("Economic opportunity", "Tools and reach help independent sellers grow.", "/info/sell-on-etsy", "Sell on Etsy"), ("Responsible growth", "We consider people and the planet in long-term decisions.", "/about", "Our mission"), ("Community", "Connection between buyers and sellers makes Etsy distinctive.", "/team", "Meet the team"), ], }, "investors": { "heading": "Investor overview", "lead": "An introduction to Etsy's marketplace, mission, and long-term approach to growth.", "body": ["Etsy connects millions of buyers with creative entrepreneurs and their unique goods.", "Company resources explain how the marketplace creates value for its community."], "section_heading": "Explore Etsy", "section_lead": "Learn more about our company story, progress, and latest updates.", "cards": [ ("Company story", "Start with Etsy's mission and marketplace model.", "/about", "About Etsy"), ("Press", "Read company and marketplace updates.", "/press", "Company news"), ("Impact", "See how responsibility informs growth.", "/impact", "View impact"), ], }, } COMPANY_INFO_ALIASES = { "etsy-inc": "about", "teams": "team", "careers": "careers", "press": "press", "impact": "impact", "investors": "investors", } REGION_COOKIE = "etsy_region" REGION_PREFERENCES = { "us": { "country": "United States", "language": "English (US)", "currency": "USD", "symbol": "$", }, "ca": { "country": "Canada", "language": "English (CA)", "currency": "CAD", "symbol": "C$", }, "gb": { "country": "United Kingdom", "language": "English (UK)", "currency": "GBP", "symbol": "£", }, "au": { "country": "Australia", "language": "English (AU)", "currency": "AUD", "symbol": "A$", }, } app = FastAPI( title="Etsy R3 persistent backend", docs_url=None, redoc_url=None, openapi_url=None, ) @app.get("/static/auth-verification.js", include_in_schema=False) async def public_registration_verification_script(): return registration_script_response(PUBLIC_REGISTRATION_VERIFICATION) app.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static") admin_app = FastAPI( title="Etsy isolated reset control", docs_url=None, redoc_url=None, openapi_url=None, ) _ADMIN_RESET_LOCK = threading.Lock() @app.middleware("http") async def runtime_headers(request: Request, call_next): original_token = request.cookies.get(SESSION_COOKIE) store = auth_store() token, session = store.ensure_session(original_token) request.state.auth_token = token request.state.auth_session = session response = await call_next(request) final_token = str(getattr(request.state, "auth_token", token)) if final_token != original_token: response.set_cookie( SESSION_COOKIE, final_token, httponly=True, samesite="lax", secure=False, path="/", max_age=30 * 24 * 60 * 60, ) response.headers["Content-Security-Policy"] = ( "default-src 'self'; img-src 'self' data:; style-src 'self'; " "script-src 'self'; connect-src 'self'; font-src 'self'; " "object-src 'none'; frame-ancestors 'none'; base-uri 'self'; " "form-action 'self'" ) response.headers["Referrer-Policy"] = "no-referrer" response.headers["X-Content-Type-Options"] = "nosniff" response.headers["X-ClawBench-Site"] = SITE_ID response.headers["X-ClawBench-Version"] = VERSION return response # --- database access ---------------------------------------------------------- _READY_PATHS: set[str] = set() _AUTH_STORES: dict[str, LocalAuthStore] = {} _SITE_BACKENDS: dict[str, object] = {} def _bound_site_backend(path: Path): """Bind the runtime before any business/auth schema creates the file.""" key = str(path.resolve()) backend = _SITE_BACKENDS.get(key) if backend is None: backend, _shared_auth = open_site_services(path.resolve()) _SITE_BACKENDS[key] = backend return backend def open_db(): """Connection with lazy migrate+seed, cached per resolved db path.""" path = db.db_path().resolve() key = str(path) _bound_site_backend(path) if key not in _READY_PATHS: db.ensure_ready(path) _READY_PATHS.add(key) return db.connect(path) def site_backend(): """Return the shared, site-bound payment runtime for this exact DB file.""" path = db.db_path().resolve() key = str(path) backend = _bound_site_backend(path) if key not in _READY_PATHS: db.ensure_ready(path) _READY_PATHS.add(key) return backend def auth_store() -> LocalAuthStore: """Return the auth kernel bound to the active site-local database. Tests switch ``CLAWBENCH_DATA_DIR`` after importing this module, so the cache is keyed by the resolved database path rather than initialized once at import time. """ path = db.db_path().resolve() key = str(path) _bound_site_backend(path) if key not in _READY_PATHS: db.ensure_ready(path) _READY_PATHS.add(key) store = _AUTH_STORES.get(key) if store is None: frozen_now = int(datetime.fromisoformat(FROZEN_CLOCK).timestamp()) mail_worker_token = os.environ.get("ETSY_HARBOR_MAIL_WORKER_TOKEN") store = LocalAuthStore( path, now=lambda: frozen_now, **( { "mail_mode": MAIL_SMTP_PENDING, "mail_worker_token": mail_worker_token, } if mail_worker_token else {} ), ) store.ensure_schema() for subject_id, credentials in SEED_AUTH_ACCOUNTS.items(): store.seed_account( subject_id=subject_id, email=credentials["email"], display_name=credentials["display_name"], password=credentials["password"], ) store.reconcile_mail(worker_token=mail_worker_token) _AUTH_STORES[key] = store return store def admin_token() -> str: return os.environ.get("CLAWBENCH_ADMIN_TOKEN", "").strip() or DEFAULT_ADMIN_TOKEN # --- verified local auth and opaque server sessions ---------------------------- def current_session(conn, request: Request) -> dict | None: auth_session = getattr(request.state, "auth_session", None) token = getattr(request.state, "auth_token", None) if not isinstance(auth_session, dict) or not isinstance(token, str): return None account = auth_session.get("account") account_id = None display_name = None owner_handle = None if isinstance(account, dict): account_id = str(account.get("subject_id") or "") or None display_name = str(account.get("display_name") or "") or None if account_id: business = conn.execute( "SELECT owner_handle, display_name FROM accounts " "WHERE account_id = ?", (account_id,), ).fetchone() if business is not None: owner_handle = str(business["owner_handle"]) display_name = str(business["display_name"]) return { "session_id": hashlib.sha256(token.encode("utf-8")).hexdigest(), "account_id": account_id, "owner_handle": owner_handle, "display_name": display_name, } def signed_in(session: dict | None) -> bool: return bool(session and session.get("account_id")) def cart_owner_key(session: dict | None) -> str | None: if session is None: return None if session.get("account_id"): return f"account:{session['account_id']}" return f"session:{session['session_id']}" # --- helpers ----------------------------------------------------------------- def cart_line_count(conn, session: dict | None) -> int: owner_key = cart_owner_key(session) if owner_key is None: return 0 row = conn.execute( "SELECT COUNT(*) AS n FROM cart_lines WHERE owner_key = ?", (owner_key,), ).fetchone() return row["n"] def favorites_count(conn, session: dict | None) -> int: if not signed_in(session): return 0 row = conn.execute( "SELECT COUNT(*) AS n FROM favorites WHERE account_id = ?", (session["account_id"],), ).fetchone() return row["n"] def base_context( conn, request: Request, session: dict | None, **values: object ) -> dict: region_id = request.cookies.get(REGION_COOKIE, "us") if region_id not in REGION_PREFERENCES: region_id = "us" context: dict[str, object] = { "request": request, "site_id": SITE_ID, "version": VERSION, "fixture_id": FIXTURE_ID, "frozen_clock": FROZEN_CLOCK, "signed_in": signed_in(session), "owner": (session or {}).get("owner_handle"), "cart_count": cart_line_count(conn, session), "favorites_count": favorites_count(conn, session), "category_menu": CATEGORY_MENU, "top_navigation": TOP_NAVIGATION, "current_path": request.url.path, "csrf": CSRF_VALUE, "session_owner": (session or {}).get("owner_handle") or "", "account_display_name": (session or {}).get("display_name") or "", "region_id": region_id, "region_preference": REGION_PREFERENCES[region_id], } context.update(values) return context def render( conn, request: Request, session: dict | None, template: str, *, status_code: int = 200, **values: object, ) -> HTMLResponse: return templates.TemplateResponse( request=request, name=template, context=base_context(conn, request, session, **values), status_code=status_code, ) async def urlencoded_form(request: Request) -> dict[str, str]: content_type = request.headers.get("content-type", "") if "application/x-www-form-urlencoded" not in content_type: return {} raw = (await request.body()).decode("utf-8", errors="replace") parsed = parse_qs(raw, keep_blank_values=True, strict_parsing=False) return {key: values[-1] for key, values in parsed.items() if values} def safe_path(value: str | None, fallback: str = "/") -> str: if value and value.startswith("/") and not value.startswith("//"): return value return fallback def listing_view(conn, listing_id: str) -> dict | None: row = db.get_listing(conn, listing_id) if row is None: return None listing = dict(row) listing["badges"] = json.loads(listing["badges_json"]) listing["cart_enabled"] = bool(listing["cart_enabled"]) return listing def resolve_search_page(conn, query: str) -> dict | None: normalized = " ".join(query.casefold().split()) row = conn.execute( "SELECT p.page_id, p.title, p.cards_count FROM search_queries q " "JOIN search_pages p ON p.page_id = q.page_id " "WHERE q.query_norm = ?", (normalized,), ).fetchone() if row is None: return None return dict(row) def search_suggestions(conn, query: str, limit: int = 8) -> list[dict]: """Known search queries matching what has been typed. The suggestion set is exactly the `search_queries` rows this database already resolves, so every suggestion leads to a real results page and no term is invented. A prefix match ranks above a mid-string match. """ normalized = " ".join(query.casefold().split()) if not normalized: return [] rows = conn.execute( "SELECT q.query_norm, p.page_id, p.title, p.cards_count " "FROM search_queries q JOIN search_pages p ON p.page_id = q.page_id " "WHERE q.query_norm LIKE ? ESCAPE '\\' ", ("%" + normalized.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%",), ).fetchall() suggestions = [] for row in rows: term = str(row["query_norm"]) suggestions.append( { "query": term, "title": str(row["title"]), "results": int(row["cards_count"]), "starts_with": term.startswith(normalized), } ) suggestions.sort(key=lambda item: (not item["starts_with"], item["query"])) for item in suggestions: del item["starts_with"] return suggestions[:limit] def search_cards(conn, page_id: str) -> list[dict]: cards = [] for row in conn.execute( "SELECT listing_id, title, price_usd, slug, image, badges_json " "FROM search_cards WHERE page_id = ? ORDER BY position", (page_id,), ): card = dict(row) card["badges"] = json.loads(card["badges_json"]) cards.append(card) return cards def catalog_cards(conn, limit: int = 16) -> list[dict]: """Return a varied, deduplicated browse grid from the captured catalog.""" cards: list[dict] = [] seen: set[str] = set() rows = conn.execute( "SELECT listing_id, title, price_usd, slug, image, badges_json " "FROM search_cards ORDER BY position, page_id" ).fetchall() for row in rows: listing_id = str(row["listing_id"]) if listing_id in seen: continue card = dict(row) card["badges"] = json.loads(card["badges_json"]) cards.append(card) seen.add(listing_id) if len(cards) >= limit: break return cards def humanize_slug(value: str) -> str: return " ".join(value.replace("_", "-").split("-")).title() def category_details(slug: str, title: str | None = None) -> dict: details = dict(CATEGORY_DETAILS.get(slug, {})) details.setdefault("title", title or humanize_slug(slug)) details.setdefault( "description", f"Explore handmade, personalized, and vintage {details['title'].lower()} from independent sellers.", ) details.setdefault("subcategories", DEFAULT_SUBCATEGORIES) return details def variation_summary(variations: dict[str, str], personalization: str) -> str: parts = [f"{label}: {value}" for label, value in variations.items()] if personalization: parts.append(f"Personalization: {personalization}") return " · ".join(parts) def normalized_idempotency_key(values: dict[str, str]) -> str: key = values.get("idempotency_key", "").strip() if not key: return "ui-" + uuid.uuid4().hex if len(key) > 120 or any(ord(character) < 32 for character in key): return "" return key def expected_version(values: dict[str, str]) -> int | None: raw = values.get("expected_version", "").strip() if not raw: return None try: parsed = int(raw) except ValueError: return -1 return parsed if parsed >= 0 else -1 def replay_response(prior, payload_digest: str): if prior is None: return None if not hmac.compare_digest(str(prior["payload_sha256"]), payload_digest): return JSONResponse( { "error": "idempotency key was already used with another payload", "effects": { "business": 0, "command": 0, "outbox": 0, "remote": 0, }, }, status_code=409, ) result = json.loads(str(prior["result_json"])) if result.get("kind") == "redirect": return RedirectResponse( str(result["location"]), status_code=int(result.get("status", 303)) ) return JSONResponse(result.get("body", {}), status_code=int(result["status"])) # --- health and admin ----------------------------------------------------------- @app.get("/healthz") async def healthz() -> JSONResponse: backend = site_backend() conn = open_db() try: migration_head = db.applied_migrations(conn)[-1] finally: conn.close() return JSONResponse( { "status": "ok", "ok": True, "site_id": SITE_ID, "stage": STAGE, "version": VERSION, "fixture_id": FIXTURE_ID, "frozen_clock": FROZEN_CLOCK, "persistent_backend": True, "registration_verification": { "mode": ( "redis-resend" if PUBLIC_REGISTRATION_VERIFICATION is not None else "browser-inbox" ), "configured": PUBLIC_REGISTRATION_VERIFICATION is not None, "provider_health": ( "checked-on-send" if PUBLIC_REGISTRATION_VERIFICATION is not None else "not-applicable" ), }, "payment_adapter": purchases.payment_adapter(backend), "payment_simulation_only": True, "site_backend": backend.lifecycle.health(), "db": { "path": str(db.db_path()), "migration_head": migration_head, "auth_migrations": auth_store().applied_migrations(), }, }, headers={ "X-WebsiteBench-Container-Build-ID": os.environ.get( "DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "") ) }, ) def _admin_request_headers(token: str) -> dict[str, str]: return { ADMIN_TOKEN_HEADER: token, ADMIN_SITE_HEADER: SITE_ID, ADMIN_SCHEMA_HEADER: db.SCHEMA_HEAD, ADMIN_SEED_HEADER: SEED_VERSION, } def _admin_token_matches(presented: str) -> bool: actual_digest = hashlib.sha256(admin_token().encode("utf-8")).digest() presented_digest = hashlib.sha256(presented.encode("utf-8")).digest() return bool(presented) and hmac.compare_digest( actual_digest, presented_digest ) def _seed_auth_account( conn, *, subject_id: str, credentials: dict[str, str] ) -> None: salt = os.urandom(16) password_hash = hashlib.scrypt( credentials["password"].encode("utf-8"), salt=salt, n=2**14, r=8, p=1, dklen=64, ) account_id = ( "account_" + hashlib.sha256(subject_id.encode("utf-8")).hexdigest()[:24] ) frozen_now = int(datetime.fromisoformat(FROZEN_CLOCK).timestamp()) conn.execute( "INSERT INTO local_auth_accounts(" "account_id,subject_id,email_normalized,display_name,password_salt," "password_hash,password_scheme,email_verified,created_at," "password_updated_at) VALUES (?,?,?,?,?,?,'scrypt-v1',1,?,?)", ( account_id, subject_id, credentials["email"].strip().casefold(), credentials["display_name"], salt, password_hash, frozen_now, frozen_now, ), ) def _reset_seed_identity(conn) -> tuple[dict[str, int], str]: tables = [ str(row[0]) for row in conn.execute( "SELECT name FROM sqlite_master WHERE type='table' " "AND name NOT LIKE 'sqlite_%' ORDER BY name" ) ] counts = { table: int( conn.execute( 'SELECT COUNT(*) FROM "' + table.replace('"', '""') + '"' ).fetchone()[0] ) for table in tables } identity = { "site_id": SITE_ID, "database": db.DB_FILENAME, "schema_head": db.SCHEMA_HEAD, "seed_version": SEED_VERSION, "counts": counts, "auth_subject_ids": sorted(SEED_AUTH_ACCOUNTS), } digest = hashlib.sha256( json.dumps( identity, ensure_ascii=False, separators=(",", ":"), sort_keys=True ).encode("utf-8") ).hexdigest() return counts, digest def _perform_admin_reset() -> dict: # The lock covers first-boot migration as well as the reset transaction. # The production control listener is single-site; this also makes # in-process/concurrent verifier calls wait for the canonical winner. with _ADMIN_RESET_LOCK: path = db.db_path() backend = site_backend() frozen_now = int(datetime.fromisoformat(FROZEN_CLOCK).timestamp()) LocalAuthStore(path, now=lambda: frozen_now).ensure_schema() conn = db.connect(path) try: conn.execute("BEGIN IMMEDIATE") db.drop_order_event_guards(conn) backend.lifecycle.reset_embedded(conn, confirm_site_id=SITE_ID) cleared_auth = {} for table in ( "local_auth_mail_outbox", "local_auth_registration_flows", "local_auth_password_reset_flows", "local_auth_sessions", "local_auth_accounts", "local_auth_mail_rate_limits", ): cleared_auth[table] = conn.execute( f"DELETE FROM {table}" ).rowcount cleared_business = {} for table in db.RESET_TABLE_ORDER: cleared_business[table] = conn.execute( f'DELETE FROM "{table}"' ).rowcount db.seed(conn, commit=False) db.install_order_event_guards(conn) for subject_id, credentials in SEED_AUTH_ACCOUNTS.items(): _seed_auth_account( conn, subject_id=subject_id, credentials=credentials ) counts, seed_digest = _reset_seed_identity(conn) conn.commit() except BaseException: conn.rollback() raise finally: conn.close() return { "reset": True, "seeded_at": FROZEN_CLOCK, "site_id": SITE_ID, "version": VERSION, "schema_head": db.SCHEMA_HEAD, "seed_version": SEED_VERSION, "counts": counts, "total_count": sum(counts.values()), "seed_digest": seed_digest, "cleared": cleared_business, "cleared_auth": cleared_auth, "auth_accounts_seeded": len(SEED_AUTH_ACCOUNTS), } @admin_app.post("/__admin/reset") async def admin_reset(request: Request) -> JSONResponse: token = request.headers.get(ADMIN_TOKEN_HEADER, "") site_identity = request.headers.get(ADMIN_SITE_HEADER, "") if site_identity != SITE_ID or not _admin_token_matches(token): return JSONResponse({"error": "not found"}, status_code=404) if ( request.headers.get(ADMIN_SCHEMA_HEADER, "") != db.SCHEMA_HEAD or request.headers.get(ADMIN_SEED_HEADER, "") != SEED_VERSION ): return JSONResponse( { "error": "stale reset precondition", "schema_head": db.SCHEMA_HEAD, "seed_version": SEED_VERSION, }, status_code=409, ) return JSONResponse(_perform_admin_reset()) # --- read routes ---------------------------------------------------------------- @app.get("/", response_class=HTMLResponse) async def home(request: Request, state: str = "loaded") -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) return render( conn, request, session, "home.html", page_title="Etsy - Shop for handmade, vintage, custom, and unique gifts for everyone", search_focused=(state == "search-focused"), ) finally: conn.close() @app.get("/info/regions", response_class=HTMLResponse) async def regions_page( request: Request, saved: str = "" ) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) region_id = request.cookies.get(REGION_COOKIE, "us") if region_id not in REGION_PREFERENCES: region_id = "us" return render( conn, request, session, "regions.html", page_title="Regions - Etsy", regions=REGION_PREFERENCES, selected_region_id=region_id, saved=(saved == "1"), errors=[], ) finally: conn.close() @app.post("/info/regions") async def regions_update(request: Request): conn = open_db() try: session = current_session(conn, request) values = await urlencoded_form(request) region_id = values.get("region", "") errors = [] if values.get("csrf") != CSRF_VALUE: errors.append("Your region form expired. Please try again.") if region_id not in REGION_PREFERENCES: errors.append("Choose one of the available regions.") if errors: selected = request.cookies.get(REGION_COOKIE, "us") if selected not in REGION_PREFERENCES: selected = "us" return render( conn, request, session, "regions.html", page_title="Regions - Etsy", regions=REGION_PREFERENCES, selected_region_id=selected, saved=False, errors=errors, status_code=422, ) response = RedirectResponse("/info/regions?saved=1", status_code=303) response.set_cookie( REGION_COOKIE, region_id, max_age=365 * 24 * 60 * 60, httponly=True, samesite="lax", secure=False, path="/", ) return response finally: conn.close() async def render_category_landing( request: Request, slug: str, *, title: str | None = None ) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) details = category_details(slug, title) return render( conn, request, session, "category.html", page_title=f"{details['title']} - Etsy", category=details, cards=catalog_cards(conn), ) finally: conn.close() @app.get("/c/{category_slug}", response_class=HTMLResponse) async def category_landing(request: Request, category_slug: str) -> HTMLResponse: return await render_category_landing(request, category_slug) @app.get("/featured/hub/{hub_slug}", response_class=HTMLResponse) async def featured_hub(request: Request, hub_slug: str) -> HTMLResponse: return await render_category_landing(request, hub_slug) @app.get("/r/curated/{curated_slug}", response_class=HTMLResponse) async def curated_landing(request: Request, curated_slug: str) -> HTMLResponse: return await render_category_landing(request, curated_slug) @app.get("/discover/{topic_slug}", response_class=HTMLResponse) async def discover_landing(request: Request, topic_slug: str) -> HTMLResponse: return await render_category_landing(request, topic_slug) @app.get("/registry", response_class=HTMLResponse) async def registry_landing(request: Request) -> HTMLResponse: return await render_category_landing(request, "registry") @app.get("/giftcards", response_class=HTMLResponse) async def gift_cards_landing(request: Request) -> HTMLResponse: return await render_category_landing(request, "giftcards") def render_company_page(request: Request, company_slug: str) -> HTMLResponse: company_page = COMPANY_PAGES[company_slug] conn = open_db() try: return render( conn, request, current_session(conn, request), "company.html", page_title=f"{company_page['heading']} - Etsy", company_page=company_page, company_navigation=COMPANY_NAVIGATION, active_company_page=company_slug, ) finally: conn.close() @app.get("/about", response_class=HTMLResponse) async def about_company_page(request: Request) -> HTMLResponse: return render_company_page(request, "about") @app.get("/team", response_class=HTMLResponse) async def team_company_page(request: Request) -> HTMLResponse: return render_company_page(request, "team") @app.get("/careers", response_class=HTMLResponse) async def careers_company_page(request: Request) -> HTMLResponse: return render_company_page(request, "careers") @app.get("/press", response_class=HTMLResponse) async def press_company_page(request: Request) -> HTMLResponse: return render_company_page(request, "press") @app.get("/impact", response_class=HTMLResponse) async def impact_company_page(request: Request) -> HTMLResponse: return render_company_page(request, "impact") @app.get("/investors", response_class=HTMLResponse) async def investors_company_page(request: Request) -> HTMLResponse: return render_company_page(request, "investors") @app.get("/help", response_class=HTMLResponse) async def help_center(request: Request) -> HTMLResponse: conn = open_db() try: return render( conn, request, current_session(conn, request), "info.html", page_title="Help Center - Etsy", heading="How can we help?", description="Find quick links for account, shopping, orders, and marketplace questions.", actions=[ ("Account and sign in", "/signin"), ("Shopping and categories", "/c/home-and-living"), ("Cart help", "/cart"), ], ) finally: conn.close() @app.get("/info/{info_slug:path}", response_class=HTMLResponse) async def information_page(request: Request, info_slug: str) -> HTMLResponse: company_slug = COMPANY_INFO_ALIASES.get(info_slug) if company_slug is not None: return render_company_page(request, company_slug) conn = open_db() try: heading, description = INFO_PAGES.get( info_slug, (humanize_slug(info_slug), "Explore more information and keep browsing Etsy."), ) return render( conn, request, current_session(conn, request), "info.html", page_title=f"{heading} - Etsy", heading=heading, description=description, actions=[("Browse categories", "/c/gifts"), ("Back to Etsy", "/")], ) finally: conn.close() @app.get("/unavailable", response_class=HTMLResponse) async def unavailable( request: Request, capability: str = "source-control", label: str = "This source control", ) -> HTMLResponse: """Truthful local terminus for unobserved source destinations/effects.""" conn = open_db() try: session = current_session(conn, request) safe_label = " ".join(label.split())[:120] or "This source control" safe_capability = " ".join(capability.split())[:120] or "source-control" return render( conn, request, session, "error.html", page_title=f"{safe_label} - unavailable", message=f"{safe_label} isn't available right now. Return to Etsy to keep browsing.", status_code=200, ) finally: conn.close() @app.get("/api/search/suggest", include_in_schema=False) async def search_suggest(q: str = "") -> JSONResponse: """Type-ahead source for the header search band. Read-only.""" conn = open_db() try: return JSONResponse( {"query": q.strip(), "results": search_suggestions(conn, q)}, headers={"Cache-Control": "no-store"}, ) finally: conn.close() @app.get("/search", response_class=HTMLResponse) async def search( request: Request, q: str = "", max: str = "", state: str = "results", ) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) normalized = ( state if state in {"results", "loading", "empty", "error"} else "results" ) page = resolve_search_page(conn, q) if q.strip() else None max_price: Decimal | None = None if max.strip(): try: max_price = Decimal(max.strip()) except ArithmeticError: max_price = None cards: list[dict] = [] chips: list[str] = [] price_filterable = False if page is not None: chips = list(PAGE_CHIPS.get(page["page_id"], [])) price_filterable = page["page_id"] in PRICE_FILTERABLE_PAGES cards = search_cards(conn, page["page_id"]) if price_filterable and max_price is not None: cards = [ card for card in cards if Decimal(card["price_usd"]) <= max_price ] chips.append(f"Under ${max_price} (item price only)") elif ( q.strip() and normalized == "results" and " ".join(q.casefold().split()) not in db.SEARCH_QUERY_SEED ): # The captured task corpus remains authoritative for its four # searches, while ordinary storefront searches still receive a # useful browse grid instead of the old dead-end empty page. cards = catalog_cards(conn) chips = ["Exclude digital downloads"] page = { "title": f"{q.strip().capitalize()} - Etsy", "cards_count": len(cards), } elif normalized == "results": normalized = "empty" return render( conn, request, session, "search.html", page_title=(page["title"] if page else f"{q} - Etsy") or "Search", query=q, max_price=(str(max_price) if max_price is not None else ""), state=normalized, page=page, cards=cards, chips=chips, price_filterable=price_filterable, sampled_note=( f"{page['cards_count']} results, with {len(cards)} featured items shown." if page else "" ), divergence_note="", ) finally: conn.close() @app.get("/listing/{listing_id}/{slug}", response_class=HTMLResponse) async def listing_detail( request: Request, listing_id: str, slug: str, state: str = "loaded" ) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) normalized = ( state if state in {"loaded", "out-of-stock", "stale-version"} else "loaded" ) listing = listing_view(conn, listing_id) if listing is None: return render( conn, request, session, "error.html", page_title="Listing not found", message="We couldn't find this listing.", status_code=404, ) favorited = False favorite_version = 0 if signed_in(session): favorited = ( conn.execute( "SELECT 1 FROM favorites WHERE account_id = ? AND listing_id = ?", (session["account_id"], listing_id), ).fetchone() is not None ) favorite_version = db.entity_version( conn, capability="favorites", entity_key=f"{session['account_id']}:{listing_id}", ) return render( conn, request, session, "listing.html", page_title=f"{listing['title']} - Etsy", listing=listing, listing_state=normalized, favorited=favorited, favorite_version=favorite_version, axes=db.listing_axes(conn, listing_id), personalization=db.personalization_config(conn, listing_id), quantity_options=[ str(number) for number in range(1, listing["max_quantity"] + 1) ], errors=[], form_values={}, ) finally: conn.close() @app.get("/signin", response_class=HTMLResponse) async def signin( request: Request, from_page: str | None = None, unauthorized: str = "", favorite: str = "", ) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) favorite_listing = listing_view(conn, favorite) if favorite else None return render( conn, request, session, "signin.html", page_title="Sign in - Etsy", from_page=safe_path(from_page, "/your/favorites"), unauthorized=(unauthorized == "1"), favorite_listing=favorite_listing, ) finally: conn.close() # --- verified registration, sign-in, recovery, mail, and sessions -------------- def _merge_anonymous_cart( conn, session_digest: str, account_id: str ) -> None: """Move the pre-authentication cart to the server-resolved account.""" anon_key = f"session:{session_digest}" account_key = f"account:{account_id}" for line in conn.execute( "SELECT * FROM cart_lines WHERE owner_key = ?", (anon_key,) ).fetchall(): existing = conn.execute( "SELECT line_token, quantity, version FROM cart_lines " "WHERE owner_key = ? AND listing_id = ? AND variations_json = ? " "AND personalization = ?", ( account_key, line["listing_id"], line["variations_json"], line["personalization"], ), ).fetchone() listing = db.get_listing(conn, line["listing_id"]) max_quantity = listing["max_quantity"] if listing else 10 if existing is not None: merged = min(existing["quantity"] + line["quantity"], max_quantity) conn.execute( "UPDATE cart_lines SET quantity = ?, version = version + 1, " "updated_at = ? WHERE line_token = ?", (merged, FROZEN_CLOCK, existing["line_token"]), ) conn.execute( "DELETE FROM cart_lines WHERE line_token = ?", (line["line_token"],), ) else: conn.execute( "UPDATE cart_lines SET owner_key = ?, version = version + 1, " "updated_at = ? WHERE line_token = ?", (account_key, FROZEN_CLOCK, line["line_token"]), ) def auth_error_message(error: AuthError) -> str: if isinstance(error, AuthRateLimited): return "Please wait before requesting another message." if isinstance(error, AuthConflict): return "That email cannot be used for this request." if isinstance(error, AuthValidationError): return str(error) return "We couldn't complete that request. Check the details and try again." def auth_subject_factory(connection, registration) -> str: opaque_account = str(registration["account_id"]) subject_id = "buyer-" + hashlib.sha256( opaque_account.encode("utf-8") ).hexdigest()[:24] local_part = str(registration["email"]).split("@", 1)[0].replace(".", "-") connection.execute( "INSERT INTO accounts(account_id, owner_handle, display_name) " "VALUES (?, ?, ?)", ( subject_id, f"{local_part}-{subject_id[-6:]}", str(registration["display_name"]), ), ) return subject_id @app.post("/auth/sign-in") async def auth_sign_in(request: Request): conn = open_db() try: values = await urlencoded_form(request) next_path = safe_path(values.get("next") or values.get("from_page"), "/") if values.get("csrf") != CSRF_VALUE: return render( conn, request, current_session(conn, request), "signin.html", page_title="Sign in - Etsy", from_page=next_path, unauthorized=False, auth_error="Your sign-in form expired. Please try again.", status_code=403, ) old_digest = hashlib.sha256( str(request.state.auth_token).encode("utf-8") ).hexdigest() try: result = auth_store().sign_in( request.state.auth_token, email=values.get("email", ""), password=values.get("password", ""), ) except AuthError: return render( conn, request, current_session(conn, request), "signin.html", page_title="Sign in - Etsy", from_page=next_path, unauthorized=False, auth_error="Email or password is invalid.", status_code=401, ) token = str(result["session_token"]) account_id = str(result["account"]["subject_id"]) request.state.auth_token = token request.state.auth_session = auth_store().resolve_session(token) _merge_anonymous_cart(conn, old_digest, account_id) conn.commit() return RedirectResponse(next_path, status_code=303) finally: conn.close() @app.post("/api/auth/send-code", include_in_schema=False) async def public_registration_send_code(request: Request) -> JSONResponse: return await send_registration_code( request, verification=PUBLIC_REGISTRATION_VERIFICATION, store=auth_store(), session_token=str(request.state.auth_token), ) @app.post("/api/auth/verify-code", include_in_schema=False) async def public_registration_verify_code(request: Request) -> JSONResponse: return await verify_registration_code( request, verification=PUBLIC_REGISTRATION_VERIFICATION, store=auth_store(), session_token=str(request.state.auth_token), ) @app.get("/register", response_class=HTMLResponse) async def register(request: Request, next: str | None = None) -> HTMLResponse: conn = open_db() try: return render( conn, request, current_session(conn, request), "register.html", page_title="Create your account - Etsy", next_path=safe_path(next, "/your/favorites"), errors=[], ) finally: conn.close() @app.post("/register") async def register_start(request: Request): conn = open_db() try: values = await urlencoded_form(request) next_path = safe_path(values.get("next"), "/your/favorites") if values.get("csrf") != CSRF_VALUE: return render( conn, request, current_session(conn, request), "register.html", page_title="Create your account - Etsy", next_path=next_path, errors=["Your registration form expired. Please try again."], status_code=403, ) if ( PUBLIC_REGISTRATION_VERIFICATION is not None and values.get("verification_fallback") != "browser-inbox" ): store = auth_store() old_digest = hashlib.sha256( str(request.state.auth_token).encode("utf-8") ).hexdigest() try: store.validate_registration_details( email=values.get("email", ""), display_name=values.get("display_name", ""), password=values.get("password", ""), ) ticket = consume_registration_ticket( verification=PUBLIC_REGISTRATION_VERIFICATION, store=store, session_token=str(request.state.auth_token), email=values.get("email", ""), ) if not ticket: return render( conn, request, current_session(conn, request), "register.html", page_title="Create your account - Etsy", next_path=next_path, errors=[ "Verify this email address before creating the account." ], status_code=422, ) result = store.complete_externally_verified_registration( str(request.state.auth_token), email=values.get("email", ""), display_name=values.get("display_name", ""), password=values.get("password", ""), subject_factory=auth_subject_factory, ) except VerificationUnavailable: try: store.start_registration( request.state.auth_token, email=values.get("email", ""), display_name=values.get("display_name", ""), password=values.get("password", ""), ) except AuthError as error: return render( conn, request, current_session(conn, request), "register.html", page_title="Create your account - Etsy", next_path=next_path, errors=[auth_error_message(error)], status_code=422, ) return RedirectResponse( f"/register/verify?next={quote(next_path, safe='/')}", status_code=303, ) except AuthError as error: return render( conn, request, current_session(conn, request), "register.html", page_title="Create your account - Etsy", next_path=next_path, errors=[auth_error_message(error)], status_code=422, ) token = str(result["session_token"]) request.state.auth_token = token request.state.auth_session = store.resolve_session(token) _merge_anonymous_cart( conn, old_digest, str(result["account"]["subject_id"]), ) conn.commit() return RedirectResponse(next_path, status_code=303) try: auth_store().start_registration( request.state.auth_token, email=values.get("email", ""), display_name=values.get("display_name", ""), password=values.get("password", ""), ) except AuthError as error: return render( conn, request, current_session(conn, request), "register.html", page_title="Create your account - Etsy", next_path=next_path, errors=[auth_error_message(error)], status_code=422, ) return RedirectResponse( f"/register/verify?next={quote(next_path, safe='/')}", status_code=303, ) finally: conn.close() @app.get("/register/verify", response_class=HTMLResponse) async def register_verify_page( request: Request, next: str | None = None ) -> HTMLResponse: conn = open_db() try: return render( conn, request, current_session(conn, request), "verify.html", page_title="Verify your email - Etsy", purpose="registration", next_path=safe_path(next, "/your/favorites"), errors=[], ) finally: conn.close() @app.post("/register/verify") async def register_verify(request: Request): conn = open_db() try: values = await urlencoded_form(request) next_path = safe_path(values.get("next"), "/your/favorites") if values.get("csrf") != CSRF_VALUE: return render( conn, request, current_session(conn, request), "verify.html", page_title="Verify your email - Etsy", purpose="registration", next_path=next_path, errors=["Your verification form expired. Please try again."], status_code=403, ) old_digest = hashlib.sha256( str(request.state.auth_token).encode("utf-8") ).hexdigest() try: auth_store().verify_registration_code( request.state.auth_token, values.get("code", ""), ) result = auth_store().complete_registration( request.state.auth_token, subject_factory=auth_subject_factory, ) except AuthError as error: return render( conn, request, current_session(conn, request), "verify.html", page_title="Verify your email - Etsy", purpose="registration", next_path=next_path, errors=[auth_error_message(error)], status_code=422, ) token = str(result["session_token"]) request.state.auth_token = token request.state.auth_session = auth_store().resolve_session(token) _merge_anonymous_cart( conn, old_digest, str(result["account"]["subject_id"]) ) conn.commit() return RedirectResponse(next_path, status_code=303) finally: conn.close() @app.get("/recover", response_class=HTMLResponse) async def recover(request: Request) -> HTMLResponse: conn = open_db() try: return render( conn, request, current_session(conn, request), "recover.html", page_title="Reset your password - Etsy", state="request", message="", errors=[], ) finally: conn.close() @app.post("/recover") async def recover_start(request: Request): conn = open_db() try: values = await urlencoded_form(request) if values.get("csrf") != CSRF_VALUE: return render( conn, request, current_session(conn, request), "recover.html", page_title="Reset your password - Etsy", state="request", message="", errors=["Your recovery form expired. Please try again."], status_code=403, ) try: result = auth_store().start_password_reset( request.state.auth_token, email=values.get("email", ""), ) message = str(result["message"]) except AuthRateLimited: message = RESET_PUBLIC_MESSAGE except AuthValidationError as error: return render( conn, request, current_session(conn, request), "recover.html", page_title="Reset your password - Etsy", state="request", message="", errors=[str(error)], status_code=422, ) return render( conn, request, current_session(conn, request), "recover.html", page_title="Reset your password - Etsy", state="verify", message=message, errors=[], ) finally: conn.close() @app.post("/recover/complete") async def recover_complete(request: Request): conn = open_db() try: values = await urlencoded_form(request) if values.get("csrf") != CSRF_VALUE: return render( conn, request, current_session(conn, request), "recover.html", page_title="Reset your password - Etsy", state="verify", message=RESET_PUBLIC_MESSAGE, errors=["Your recovery form expired. Please try again."], status_code=403, ) try: auth_store().verify_password_reset_code( request.state.auth_token, values.get("code", ""), ) token = auth_store().complete_password_reset( request.state.auth_token, new_password=values.get("new_password", ""), ) except AuthError as error: return render( conn, request, current_session(conn, request), "recover.html", page_title="Reset your password - Etsy", state="verify", message=RESET_PUBLIC_MESSAGE, errors=[auth_error_message(error)], status_code=422, ) request.state.auth_token = token request.state.auth_session = auth_store().resolve_session(token) return RedirectResponse("/", status_code=303) finally: conn.close() @app.get("/auth/inbox", response_class=HTMLResponse) async def auth_inbox( request: Request, purpose: str = "registration" ) -> HTMLResponse: conn = open_db() try: selected = ( "password-reset" if purpose == "password-reset" else "registration" ) message = auth_store().local_mail_for_session( request.state.auth_token, purpose=selected, ) return render( conn, request, current_session(conn, request), "inbox.html", page_title="Verification message - Etsy", purpose=selected, message=message, ) finally: conn.close() @app.post("/auth/sign-out") async def auth_sign_out(request: Request) -> RedirectResponse: auth_store().sign_out(request.state.auth_token) token = auth_store().create_anonymous_session() request.state.auth_token = token request.state.auth_session = auth_store().resolve_session(token) return RedirectResponse("/", status_code=303) @app.post("/__test/session") async def test_session(request: Request): """Admin-bound seeded login; it is never linked from public pages.""" if not hmac.compare_digest( request.headers.get(ADMIN_TOKEN_HEADER, ""), admin_token() ): return JSONResponse({"error": "not found"}, status_code=404) values = await urlencoded_form(request) account_id = values.get("account_id", "alex") credentials = SEED_AUTH_ACCOUNTS.get(account_id) if credentials is None: return JSONResponse({"error": "not found"}, status_code=404) old_digest = hashlib.sha256( str(request.state.auth_token).encode("utf-8") ).hexdigest() result = auth_store().sign_in( request.state.auth_token, email=credentials["email"], password=credentials["password"], ) token = str(result["session_token"]) request.state.auth_token = token request.state.auth_session = auth_store().resolve_session(token) conn = open_db() try: _merge_anonymous_cart(conn, old_digest, account_id) conn.commit() finally: conn.close() return RedirectResponse( safe_path(values.get("next") or values.get("from_page"), "/"), status_code=303, ) # --- cart mutations --------------------------------------------------------------- def _validate_variations( conn, listing_id: str, axes: list[dict], values: dict[str, str] ) -> tuple[dict[str, str], list[str]]: """A complete tuple names one selectable option per configured axis.""" variations: dict[str, str] = {} errors: list[str] = [] for axis in axes: posted = values.get(axis["field"], "") selectable = { option["value"] for option in axis["options"] if option["selectable"] } if not posted: errors.append(f"Please select an option for {axis['label']}.") elif posted not in selectable: errors.append( f"{posted!r} is not an available option for {axis['label']}." ) else: variations[axis["label"]] = posted return variations, errors def _validate_personalization( personalization_cfg: dict, text: str ) -> list[str]: """Generic personalization rules: required-empty and over-limit are rejected; any other text is accepted verbatim (rendered escaped).""" errors: list[str] = [] if not personalization_cfg["enabled"]: if text.strip(): errors.append("This listing does not accept personalization.") return errors if personalization_cfg["required"] and not text.strip(): errors.append("Personalization is required for this item.") limit = personalization_cfg["char_limit"] if limit and len(text) > limit: errors.append( f"Personalization must be {limit} characters or fewer." ) return errors def _validate_quantity(raw: str, max_quantity: int) -> tuple[int, list[str]]: try: quantity = int(raw) except (TypeError, ValueError): return 0, [f"Quantity must be a whole number between 1 and {max_quantity}."] if quantity < 1 or quantity > max_quantity: return 0, [f"Quantity must be between 1 and {max_quantity}."] return quantity, [] @app.post("/cart/listing") async def cart_add(request: Request): """Add-to-cart: server-owned identity, version, availability, and price. The client can only name a known listing id, one selectable option per configured axis, personalization text within the listing's rules, and a quantity. Any client-submitted price field is ignored entirely. """ conn = open_db() try: session = current_session(conn, request) values = await urlencoded_form(request) listing_id = values.get("listing_id", "") listing = listing_view(conn, listing_id) if listing is None: return render( conn, request, session, "error.html", page_title="Cart refusal", message=( "Unknown or foreign listing identity: the cart contract " "only accepts server-validated listings." ), status_code=404, ) if not listing["cart_enabled"]: return render( conn, request, session, "error.html", page_title="Cart refusal", message="This listing cannot be added to a cart.", status_code=422, ) if ( values.get("listing_version") != listing["version"] or listing["stock_state"] != "in-stock" ): return render( conn, request, session, "error.html", page_title="Stale listing version", message=( "This listing version is stale or out of stock. Refresh " "the listing and try again; no cart line was created." ), status_code=409, ) axes = db.listing_axes(conn, listing_id) personalization_cfg = db.personalization_config(conn, listing_id) variations, errors = _validate_variations(conn, listing_id, axes, values) personalization = values.get("personalization", "") errors.extend( _validate_personalization(personalization_cfg, personalization) ) quantity, quantity_errors = _validate_quantity( values.get("quantity", "1"), listing["max_quantity"] ) errors.extend(quantity_errors) if not errors and variations and db.combo_unavailable( conn, listing_id, variations ): errors.append( "This combination of options is unavailable for this listing." ) if errors: favorited = False favorite_version = 0 if signed_in(session): favorited = ( conn.execute( "SELECT 1 FROM favorites WHERE account_id = ? " "AND listing_id = ?", (session["account_id"], listing_id), ).fetchone() is not None ) favorite_version = db.entity_version( conn, capability="favorites", entity_key=f"{session['account_id']}:{listing_id}", ) return render( conn, request, session, "listing.html", page_title=f"{listing['title']} - Etsy", listing=listing, listing_state="loaded", favorited=favorited, favorite_version=favorite_version, axes=axes, personalization=personalization_cfg, quantity_options=[ str(number) for number in range(1, listing["max_quantity"] + 1) ], errors=errors, form_values=values, status_code=422, ) # Server-computed price only; client fields are never read. unit_cents = db.unit_price_cents(conn, listing_id, variations) if session is None: return JSONResponse({"error": "session unavailable"}, status_code=503) owner_key = cart_owner_key(session) variations_json = db.combo_key(variations) entity_key = hashlib.sha256( f"{owner_key}\n{listing_id}\n{variations_json}\n{personalization}".encode( "utf-8" ) ).hexdigest() idempotency_key = normalized_idempotency_key(values) if not idempotency_key: return JSONResponse( {"error": "invalid idempotency key"}, status_code=422 ) payload = { "operation": "add", "listing_id": listing_id, "listing_version": listing["version"], "variations": variations, "personalization": personalization, "quantity": quantity, "next_action": values.get("next_action", "cart"), } payload_digest = db.payload_sha256(payload) requested_version = expected_version(values) conn.execute("BEGIN IMMEDIATE") prior = db.prior_command( conn, capability="cart-lifecycle", owner_scope=str(owner_key), idempotency_key=idempotency_key, ) replay = replay_response(prior, payload_digest) if replay is not None: conn.rollback() return replay current_version = db.entity_version( conn, capability="cart-lifecycle", entity_key=entity_key ) if requested_version is not None and requested_version != current_version: conn.rollback() return JSONResponse( { "error": "stale cart version", "current_version": current_version, "effects": { "business": 0, "command": 0, "outbox": 0, "remote": 0, }, }, status_code=409, ) existing = conn.execute( "SELECT line_token, quantity, version FROM cart_lines " "WHERE owner_key = ? AND listing_id = ? AND variations_json = ? " "AND personalization = ?", (owner_key, listing_id, variations_json, personalization), ).fetchone() if existing is not None: merged = min( existing["quantity"] + quantity, listing["max_quantity"] ) conn.execute( "UPDATE cart_lines SET quantity = ?, unit_price_cents = ?, " "version = version + 1, updated_at = ? WHERE line_token = ?", (merged, unit_cents, FROZEN_CLOCK, existing["line_token"]), ) location = "/cart?notice=merged" else: line_token = uuid.uuid4().hex conn.execute( "INSERT INTO cart_lines (line_token, owner_key, listing_id, " " listing_version, variations_json, personalization, quantity," " unit_price_cents, created_at, updated_at, version) " "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( line_token, owner_key, listing_id, listing["version"], variations_json, personalization, quantity, unit_cents, FROZEN_CLOCK, FROZEN_CLOCK, current_version + 1, ), ) location = f"/cart?added={listing_id}" if values.get("next_action") == "checkout": location = "/checkout" result = {"kind": "redirect", "location": location, "status": 303} db.commit_command( conn, capability="cart-lifecycle", owner_scope=str(owner_key), idempotency_key=idempotency_key, payload_digest=payload_digest, result=result, entity_key=entity_key, next_version=current_version + 1, ) conn.commit() return RedirectResponse(location, status_code=303) finally: conn.close() def _find_owned_line(conn, session: dict | None, line_token: str): """Cart lines are opaque: a token outside the caller's scope resolves exactly like a nonexistent one (404, no existence leak).""" owner_key = cart_owner_key(session) if owner_key is None or not line_token: return None return conn.execute( "SELECT * FROM cart_lines WHERE line_token = ? AND owner_key = ?", (line_token, owner_key), ).fetchone() @app.post("/cart/update") async def cart_update(request: Request): """Server-side quantity update on an existing opaque cart line.""" conn = open_db() try: session = current_session(conn, request) values = await urlencoded_form(request) line = _find_owned_line(conn, session, values.get("line_token", "")) if line is None: return render( conn, request, session, "error.html", page_title="Cart refusal", message="Unknown cart line for this session.", status_code=404, ) listing = db.get_listing(conn, line["listing_id"]) max_quantity = listing["max_quantity"] if listing else 10 quantity, errors = _validate_quantity( values.get("quantity", ""), max_quantity ) if errors: return render( conn, request, session, "error.html", page_title="Cart refusal", message=" ".join(errors), status_code=422, ) owner_key = cart_owner_key(session) idempotency_key = normalized_idempotency_key(values) if not idempotency_key: return JSONResponse( {"error": "invalid idempotency key"}, status_code=422 ) payload = { "operation": "update", "line_token": str(line["line_token"]), "quantity": quantity, } payload_digest = db.payload_sha256(payload) requested_version = expected_version(values) conn.execute("BEGIN IMMEDIATE") line = _find_owned_line(conn, session, str(line["line_token"])) if line is None: conn.rollback() return JSONResponse({"error": "unknown cart line"}, status_code=404) prior = db.prior_command( conn, capability="cart-lifecycle", owner_scope=str(owner_key), idempotency_key=idempotency_key, ) replay = replay_response(prior, payload_digest) if replay is not None: conn.rollback() return replay if requested_version is not None and requested_version != int(line["version"]): conn.rollback() return JSONResponse( {"error": "stale cart line", "current_version": int(line["version"])}, status_code=409, ) next_version = int(line["version"]) + 1 conn.execute( "UPDATE cart_lines SET quantity = ?, version = ?, updated_at = ? " "WHERE line_token = ?", (quantity, next_version, FROZEN_CLOCK, line["line_token"]), ) result = {"kind": "redirect", "location": "/cart?notice=updated", "status": 303} db.commit_command( conn, capability="cart-lifecycle", owner_scope=str(owner_key), idempotency_key=idempotency_key, payload_digest=payload_digest, result=result, entity_key=f"cart-line:{line['line_token']}", next_version=next_version, ) conn.commit() return RedirectResponse("/cart?notice=updated", status_code=303) finally: conn.close() @app.post("/cart/remove") async def cart_remove(request: Request): conn = open_db() try: session = current_session(conn, request) values = await urlencoded_form(request) line = _find_owned_line(conn, session, values.get("line_token", "")) if line is None: return render( conn, request, session, "error.html", page_title="Cart refusal", message="Unknown cart line for this session.", status_code=404, ) owner_key = cart_owner_key(session) idempotency_key = normalized_idempotency_key(values) if not idempotency_key: return JSONResponse( {"error": "invalid idempotency key"}, status_code=422 ) payload = {"operation": "remove", "line_token": str(line["line_token"])} payload_digest = db.payload_sha256(payload) requested_version = expected_version(values) conn.execute("BEGIN IMMEDIATE") line = _find_owned_line(conn, session, str(line["line_token"])) if line is None: conn.rollback() return JSONResponse({"error": "unknown cart line"}, status_code=404) prior = db.prior_command( conn, capability="cart-lifecycle", owner_scope=str(owner_key), idempotency_key=idempotency_key, ) replay = replay_response(prior, payload_digest) if replay is not None: conn.rollback() return replay if requested_version is not None and requested_version != int(line["version"]): conn.rollback() return JSONResponse( {"error": "stale cart line", "current_version": int(line["version"])}, status_code=409, ) next_version = int(line["version"]) + 1 conn.execute( "DELETE FROM cart_lines WHERE line_token = ?", (line["line_token"],), ) result = {"kind": "redirect", "location": "/cart", "status": 303} db.commit_command( conn, capability="cart-lifecycle", owner_scope=str(owner_key), idempotency_key=idempotency_key, payload_digest=payload_digest, result=result, entity_key=f"cart-line:{line['line_token']}", next_version=next_version, ) conn.commit() return RedirectResponse("/cart", status_code=303) finally: conn.close() @app.get("/cart", response_class=HTMLResponse) async def cart( request: Request, added: str = "", notice: str = "" ) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) owner_key = cart_owner_key(session) lines = [] total = Decimal("0.00") if owner_key is not None: for line in conn.execute( "SELECT c.*, l.title, l.slug, l.image, l.max_quantity " "FROM cart_lines c JOIN listings l " "ON l.listing_id = c.listing_id " "WHERE c.owner_key = ? ORDER BY c.rowid", (owner_key,), ): unit = Decimal(line["unit_price_cents"]) / 100 subtotal = unit * line["quantity"] total += subtotal lines.append( { "line_token": line["line_token"], "listing_id": line["listing_id"], "title": line["title"], "slug": line["slug"], "image": line["image"], "summary": variation_summary( json.loads(line["variations_json"]), line["personalization"], ), "quantity": line["quantity"], "version": line["version"], "max_quantity": line["max_quantity"], "unit_price": f"${unit:.2f}", "subtotal": f"${subtotal:.2f}", } ) return render( conn, request, session, "cart.html", page_title="Your cart - Etsy", lines=lines, item_total=f"${total:.2f}", added=added, notice=notice, compact_footer=True, ) finally: conn.close() # --- checkout, test payment, and immutable orders ------------------------------ def _checkout_signin() -> RedirectResponse: return RedirectResponse("/signin?from_page=/checkout&unauthorized=1", status_code=303) def _cart_item_total(conn, owner_key: str) -> str: cents = conn.execute( "SELECT COALESCE(SUM(unit_price_cents * quantity),0) FROM cart_lines " "WHERE owner_key=?", (owner_key,), ).fetchone()[0] return purchases.money(int(cents)) def _render_checkout_page( conn, request: Request, session: dict, checkout: dict, *, payment_error: str = "", cancelled: bool = False, status_code: int = 200, ) -> HTMLResponse: backend = site_backend() return render( conn, request, session, "checkout.html", page_title="Review and pay - Etsy", checkout=purchases.decorate_checkout(conn, checkout), adapter=purchases.payment_adapter(backend), scenarios=purchases.payment_scenarios(backend), payment_error=payment_error, cancelled=cancelled, status_code=status_code, ) @app.get("/checkout", response_class=HTMLResponse) async def checkout_address(request: Request) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return _checkout_signin() owner_key = cart_owner_key(session) if cart_line_count(conn, session) == 0 or owner_key is None: return RedirectResponse("/cart", status_code=303) return render( conn, request, session, "checkout_address.html", page_title="Shipping details - Etsy", values={}, errors=[], item_total=_cart_item_total(conn, owner_key), ) finally: conn.close() @app.post("/checkout") async def checkout_create(request: Request): conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return _checkout_signin() values = await urlencoded_form(request) address, errors = purchases.validate_address(values) owner_key = cart_owner_key(session) if values.get("csrf") != CSRF_VALUE: errors.insert(0, "Your checkout form expired. Please try again.") if owner_key is None or cart_line_count(conn, session) == 0: return RedirectResponse("/cart", status_code=303) if errors: return render( conn, request, session, "checkout_address.html", page_title="Shipping details - Etsy", values=values, errors=errors, item_total=_cart_item_total(conn, owner_key), status_code=422, ) backend = site_backend() try: conn.execute("BEGIN IMMEDIATE") checkout = purchases.create_checkout( conn, backend, account_id=str(session["account_id"]), owner_key=owner_key, address=address, ) conn.commit() except purchases.PurchaseError as exc: conn.rollback() return render( conn, request, session, "checkout_address.html", page_title="Shipping details - Etsy", values=values, errors=[str(exc)], item_total=_cart_item_total(conn, owner_key), status_code=409, ) return RedirectResponse(f"/checkout/{checkout['checkout_id']}", status_code=303) finally: conn.close() @app.get("/checkout/stripe-return", response_class=HTMLResponse) async def checkout_stripe_return( request: Request, session_id: str = "", cancelled: str = "" ): conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return _checkout_signin() backend = site_backend() if purchases.payment_adapter(backend) != "stripe-test": return RedirectResponse("/cart", status_code=303) try: snapshot = StripeTestGateway(backend.config).retrieve_checkout_session(session_id) metadata = snapshot.get("metadata") or {} checkout = purchases.checkout_by_flow(conn, str(metadata.get("flow_id", ""))) if checkout is None or checkout["account_id"] != session["account_id"]: raise purchases.PurchaseError("Stripe test Checkout was not found.") if cancelled == "1": return _render_checkout_page( conn, request, session, checkout, cancelled=True ) conn.execute("BEGIN IMMEDIATE") order = purchases.approve_verified_stripe( conn, backend, checkout=checkout, provider_session_id=session_id, provider_snapshot=snapshot, ) conn.commit() return RedirectResponse(f"/orders/{order['order_id']}", status_code=303) except (purchases.PurchaseError, StripeTestError, StripeTestUnavailable) as exc: conn.rollback() return render( conn, request, session, "error.html", page_title="Stripe test Checkout - Etsy", message=str(exc), status_code=409, ) finally: conn.close() @app.post("/api/stripe/webhook", include_in_schema=False) async def stripe_webhook(request: Request) -> JSONResponse: """Consume only events whose Stripe signature was verified by the edge.""" if request.headers.get("x-websitebench-stripe-verified") != "1": return JSONResponse({"error": "not found"}, status_code=404) raw = await request.body() if len(raw) > 64 * 1024: return JSONResponse({"error": "event too large"}, status_code=413) try: event = json.loads(raw) provider = event["data"]["object"] session_id = str(provider["id"]) except (KeyError, TypeError, UnicodeDecodeError, json.JSONDecodeError): return JSONResponse({"error": "invalid event"}, status_code=422) if event.get("type") not in { "checkout.session.completed", "checkout.session.async_payment_succeeded", }: return JSONResponse({"received": True}) conn = open_db() try: backend = site_backend() try: snapshot = StripeTestGateway(backend.config).retrieve_checkout_session(session_id) metadata = snapshot.get("metadata") or {} checkout = purchases.checkout_by_flow(conn, str(metadata.get("flow_id", ""))) if checkout is None: raise purchases.PurchaseError("checkout not found") conn.execute("BEGIN IMMEDIATE") order = purchases.approve_verified_stripe( conn, backend, checkout=checkout, provider_session_id=session_id, provider_snapshot=snapshot, ) conn.commit() return JSONResponse({"received": True, "order_id": order["order_id"]}) except (purchases.PurchaseError, StripeTestError, StripeTestUnavailable): conn.rollback() return JSONResponse({"error": "event rejected"}, status_code=409) finally: conn.close() @app.get("/checkout/{checkout_id}", response_class=HTMLResponse) async def checkout_review(request: Request, checkout_id: str) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return _checkout_signin() checkout = purchases.checkout_for_owner( conn, str(session["account_id"]), checkout_id ) if checkout is None: return render( conn, request, session, "error.html", page_title="Checkout not found", message="We couldn't find that checkout.", status_code=404 ) existing = conn.execute( "SELECT order_id FROM orders WHERE checkout_id=? AND account_id=?", (checkout_id, session["account_id"]), ).fetchone() if existing is not None: return RedirectResponse(f"/orders/{existing['order_id']}", status_code=303) return _render_checkout_page(conn, request, session, checkout) finally: conn.close() @app.post("/checkout/{checkout_id}/pay") async def checkout_pay(request: Request, checkout_id: str): conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return _checkout_signin() values = await urlencoded_form(request) checkout = purchases.checkout_for_owner( conn, str(session["account_id"]), checkout_id ) if checkout is None: return JSONResponse({"error": "checkout not found"}, status_code=404) if values.get("csrf") != CSRF_VALUE: return _render_checkout_page( conn, request, session, checkout, payment_error="Your payment form expired. Please try again.", status_code=403, ) backend = site_backend() if purchases.payment_adapter(backend) == "local-sandbox": try: conn.execute("BEGIN IMMEDIATE") outcome, order = purchases.attempt_local_payment( conn, backend, account_id=str(session["account_id"]), checkout_id=checkout_id, scenario_id=values.get("scenario_id", ""), ) conn.commit() except purchases.PurchaseError as exc: conn.rollback() return _render_checkout_page( conn, request, session, checkout, payment_error=str(exc), status_code=409 ) if order is not None: return RedirectResponse(f"/orders/{order['order_id']}", status_code=303) label = "declined" if outcome == "DECLINED" else "not completed" return _render_checkout_page( conn, request, session, purchases.checkout_for_owner(conn, str(session["account_id"]), checkout_id), payment_error=f"The test payment was {label}. Try another test outcome.", status_code=402, ) try: flow = purchases.payment_flow(conn, checkout) lines = [ StripeTestLineItem( name=str(line["title"]), amount_minor=int(line["unit_price_cents"]), quantity=int(line["quantity"]), ) for line in purchases.checkout_lines(conn, checkout_id) ] if int(checkout["tax_cents"]): lines.append( StripeTestLineItem( name="Estimated sales tax", amount_minor=int(checkout["tax_cents"]), ) ) email = conn.execute( "SELECT email_normalized FROM local_auth_accounts WHERE subject_id=?", (session["account_id"],), ).fetchone() if email is None: raise purchases.PurchaseError("Checkout email is unavailable.") provider = StripeTestGateway(backend.config).create_checkout_session( flow=flow, customer_email=str(email["email_normalized"]), line_items=lines, ) return RedirectResponse(str(provider["url"]), status_code=303) except (purchases.PurchaseError, StripeTestError, StripeTestUnavailable) as exc: return _render_checkout_page( conn, request, session, checkout, payment_error=str(exc), status_code=503 ) finally: conn.close() @app.get("/orders/{order_id}", response_class=HTMLResponse) async def order_detail(request: Request, order_id: str) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return RedirectResponse( f"/signin?from_page=/orders/{quote(order_id)}&unauthorized=1", status_code=303, ) order = purchases.order_for_owner(conn, str(session["account_id"]), order_id) if order is None: return render( conn, request, session, "error.html", page_title="Order not found", message="We couldn't find that order.", status_code=404 ) return render( conn, request, session, "order.html", page_title="Order confirmed - Etsy", order=order ) finally: conn.close() @app.get("/your/purchases", response_class=HTMLResponse) async def purchase_history(request: Request) -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return RedirectResponse( "/signin?from_page=/your/purchases&unauthorized=1", status_code=303 ) return render( conn, request, session, "purchases.html", page_title="Purchases - Etsy", orders=purchases.orders_for_owner(conn, str(session["account_id"])) ) finally: conn.close() # --- favorites -------------------------------------------------------------------- @app.post("/favorites/toggle") async def favorites_toggle(request: Request): conn = open_db() try: session = current_session(conn, request) values = await urlencoded_form(request) next_path = safe_path(values.get("next"), "/your/favorites") if not signed_in(session): listing_id = values.get("listing_id", "") return RedirectResponse( f"/signin?from_page={quote(next_path, safe='/')}&unauthorized=1" f"&favorite={quote(listing_id)}", status_code=303, ) listing_id = values.get("listing_id", "") if db.get_listing(conn, listing_id) is None: return render( conn, request, session, "error.html", page_title="Favorites refusal", message=( "Unknown listing identity: favorites only accept " "server-validated listings." ), status_code=404, ) account_id = session["account_id"] action = values.get("action", "add") if action not in {"add", "remove"}: return JSONResponse( { "error": "invalid favorite action", "effects": { "business": 0, "command": 0, "outbox": 0, "remote": 0, }, }, status_code=422, ) idempotency_key = normalized_idempotency_key(values) if not idempotency_key: return JSONResponse( {"error": "invalid idempotency key"}, status_code=422 ) owner_scope = str(account_id) entity_key = f"{account_id}:{listing_id}" payload = {"operation": action, "listing_id": listing_id} payload_digest = db.payload_sha256(payload) requested_version = expected_version(values) conn.execute("BEGIN IMMEDIATE") prior = db.prior_command( conn, capability="favorites", owner_scope=owner_scope, idempotency_key=idempotency_key, ) replay = replay_response(prior, payload_digest) if replay is not None: conn.rollback() return replay current_version = db.entity_version( conn, capability="favorites", entity_key=entity_key ) if requested_version is not None and requested_version != current_version: conn.rollback() return JSONResponse( { "error": "stale favorite version", "current_version": current_version, "effects": { "business": 0, "command": 0, "outbox": 0, "remote": 0, }, }, status_code=409, ) exists = ( conn.execute( "SELECT 1 FROM favorites WHERE account_id = ? AND listing_id = ?", (account_id, listing_id), ).fetchone() is not None ) if action == "remove": conn.execute( "DELETE FROM favorites WHERE account_id = ? AND listing_id = ?", (account_id, listing_id), ) toast = "removed" if exists else "already-absent" else: # Idempotent add: repeating a favorite never duplicates it. conn.execute( "INSERT OR IGNORE INTO favorites " "(account_id, listing_id, created_at, version) VALUES (?, ?, ?, ?)", (account_id, listing_id, FROZEN_CLOCK, current_version + 1), ) toast = "already-favorited" if exists else "favorited" separator = "&" if "?" in next_path else "?" location = f"{next_path}{separator}toast={toast}" result = {"kind": "redirect", "location": location, "status": 303} db.commit_command( conn, capability="favorites", owner_scope=owner_scope, idempotency_key=idempotency_key, payload_digest=payload_digest, result=result, entity_key=entity_key, next_version=current_version + 1, ) conn.commit() return RedirectResponse(location, status_code=303) finally: conn.close() @app.get("/your/favorites", response_class=HTMLResponse) async def favorites(request: Request, toast: str = "") -> HTMLResponse: conn = open_db() try: session = current_session(conn, request) if not signed_in(session): return RedirectResponse( "/signin?from_page=/your/favorites&unauthorized=1", status_code=303, ) items = [] for row in conn.execute( "SELECT f.listing_id, f.version, l.title, l.slug, l.image, l.price_now " "FROM favorites f JOIN listings l ON l.listing_id = f.listing_id " "WHERE f.account_id = ? ORDER BY f.rowid", (session["account_id"],), ): items.append( { "listing_id": row["listing_id"], "title": row["title"], "slug": row["slug"], "image": row["image"], "price": row["price_now"], "version": db.entity_version( conn, capability="favorites", entity_key=f"{session['account_id']}:{row['listing_id']}", ), } ) return render( conn, request, session, "favorites.html", page_title="Your favorites - Etsy", items=items, toast=toast, ) finally: conn.close() def main() -> None: if os.environ.get("CLAWBENCH_ADMIN_LISTENER", "") == "1": port = int(os.environ.get("CLAWBENCH_ADMIN_PORT", "18532")) uvicorn.run( admin_app, host="127.0.0.1", port=port, access_log=True ) return port = int(os.environ.get("PORT", "8532")) uvicorn.run(app, host="127.0.0.1", port=port, access_log=True) if __name__ == "__main__": main()