"""Capterra WebsiteBench clone — persistent backend app. Routes stay identical to the accepted R2 frontend surface; business logic (accounts, signed-cookie sessions, review drafts/revisions/submissions, admin reset) is server-side and backed by SQLite via clone/backend/db.py. The database path and site identity come only from ``backend/runtime.json``. Validation is generic source-site behavior: any whole-star rating 1-5 with non-empty text is accepted; benchmark values are ordinary seed data. """ from __future__ import annotations import functools import importlib.util import hashlib import hmac import http.client import ipaddress import json import os import re import secrets import sys import time import unicodedata from collections.abc import Mapping from contextlib import asynccontextmanager from pathlib import Path from urllib.parse import parse_qs, quote, urlencode, urlsplit ROOT = Path(__file__).resolve().parent if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) import uvicorn from fastapi import FastAPI, Request, Response from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse from starlette.exceptions import HTTPException as StarletteHTTPException from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from websitebench.local_clone_auth import ( MAIL_LOCAL_ONLY, MAIL_OUTCOME_UNKNOWN, MAIL_SMTP_PENDING, RESET_PUBLIC_MESSAGE, AuthConflict, AuthError, AuthLocked, AuthRateLimited, AuthRejected, AuthValidationError, LocalAuthStore, ) from websitebench.site_backend import load_runtime from backend.site_backend_integration import open_site_services from backend.categories import ( category_index, category_label, ) from websitebench.public_clone_auth import ( VerificationUnavailable, load_public_clone_registration_verification, ) from websitebench.public_clone_auth.fastapi import ( consume_registration_ticket, registration_script_response, send_registration_code, verify_registration_code, ) SCOPE_ROOT = ROOT.parent / "scope" def _load_scope_routes() -> dict[str, dict[str, object]]: """Load the accepted control contract used by the offline UI.""" payload = json.loads( (SCOPE_ROOT / "routes.json").read_text(encoding="utf-8") ) return {str(route["id"]): route for route in payload["routes"]} SCOPE_ROUTES = _load_scope_routes() def _load_backend_db(): module_name = "capterra_clone_backend_db" if module_name in sys.modules: return sys.modules[module_name] spec = importlib.util.spec_from_file_location( module_name, ROOT / "backend" / "db.py" ) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) return module backend_db = _load_backend_db() SITE_BACKEND_RUNTIME = load_runtime(ROOT.parent / "backend" / "runtime.json") SITE_ID = backend_db.SITE_ID PUBLIC_REGISTRATION_VERIFICATION = load_public_clone_registration_verification() VERSION = "capterra-r3-backend-2026-08-02.19" FIXTURE_ID = "capterra-v2-474-h2" FROZEN_CLOCK = backend_db.FROZEN_CLOCK PRODUCT_ID = backend_db.PRODUCT_ID PRODUCT_NAME = backend_db.PRODUCT_NAME RECEIPT_ID = backend_db.RECEIPT_CODE REVIEW_TEXT_MAX_CODEPOINTS = 2000 SESSION_COOKIE = "clawbench_capterra_h2" AUTH_SESSION_COOKIE = SITE_BACKEND_RUNTIME.cookie_name CSRF_VALUE = "capterra-h2-public-fixture" ADMIN_TOKEN_HEADER = "X-WebsiteBench-Admin-Token" LEGACY_ADMIN_TOKEN_HEADER = "X-Clawbench-Admin-Token" ASSETS_BASE = "/static/assets/source-current/2026-07-25" PUBLIC_REPLAY_ROOT = ROOT / "static" / "public-replay" / "pages" PRIMARY_ACCOUNT_SLUG = backend_db.PRIMARY_ACCOUNT[0] SECONDARY_ACCOUNT_SLUG = backend_db.SECONDARY_ACCOUNT[0] KNOWN_ACCOUNT_SLUGS = { PRIMARY_ACCOUNT_SLUG, SECONDARY_ACCOUNT_SLUG, } REVIEW_PAGE_SIZE = 25 REVIEW_PAGE_COUNT = 9 R2_ROUTE_PATHS = { "auth-register": "/auth/register", "auth-register-verify": "/auth/register/verify", "auth-login": "/auth/login", "auth-logout": "/auth/logout", "auth-password-forgot": "/auth/password/forgot", "auth-password-verify": "/auth/password/verify", "auth-password-reset": "/auth/password/reset", "auth-local-inbox": "/auth/local-inbox", "local-comparison": "/compare", "software-favorites": f"/favorites/software/{PRODUCT_ID}", } R2_ROUTE_UI = { "auth-register": { "eyebrow": "Local Capterra account", "title": "Create a local Capterra account", "purpose": "Use this site’s account to write reviews, compare products, and save software here.", "field_label": "Email address", "placeholder": "name@example.com", "action": "Continue", }, "auth-register-verify": { "eyebrow": "Email verification", "title": "Verify your email address", "purpose": "Enter the six-character code from local Capterra messages.", "field_label": "Six-character code", "placeholder": "ABC123", "action": "Verify email", }, "auth-login": { "eyebrow": "Local Capterra account", "title": "Sign in to your local account", "purpose": "Access reviews, comparisons, and saved software on this site.", "field_label": "Email address", "placeholder": "name@example.com", "action": "Sign in", }, "auth-logout": { "eyebrow": "Your account", "title": "Sign out of Capterra", "purpose": "Revoke this browser session when you have finished.", "field_label": "Current session", "placeholder": "Signed in", "action": "Sign out", }, "auth-password-forgot": { "eyebrow": "Account recovery", "title": "Reset your password", "purpose": "If the account exists here, a recovery message will appear in local Capterra messages.", "field_label": "Account email", "placeholder": "name@example.com", "action": "Continue", }, "auth-password-verify": { "eyebrow": "Account recovery", "title": "Enter your verification code", "purpose": "Open local Capterra messages for the six-character code.", "field_label": "Six-character code", "placeholder": "ABC123", "action": "Verify code", }, "auth-password-reset": { "eyebrow": "Account recovery", "title": "Choose a new password", "purpose": "Create a secure password you haven’t used before.", "field_label": "New password", "placeholder": "Use 12 or more characters", "action": "Update password", }, "auth-local-inbox": { "eyebrow": "Messages", "title": "Your Capterra messages", "purpose": "Review messages stored for this browser session. External email is not implied.", "field_label": "Search messages", "placeholder": "Search your inbox", "action": "View messages", }, "local-comparison": { "eyebrow": "Buyer workspace", "title": "Compare software", "purpose": "See product ratings, pricing, and features side by side.", "field_label": "Products selected", "placeholder": "Notion and one alternative", "action": "Update comparison", }, "software-favorites": { "eyebrow": "Buyer workspace", "title": "Save software to favorites", "purpose": "Keep products you’re interested in together for easy comparison.", "field_label": "Selected product", "placeholder": "Notion", "action": "Update favorites", }, } R2_STATE_COPY = { "entry": ("Ready for input", "Enter your information to continue."), "invalid": ( "Check the highlighted value", "Review the field below and try again.", ), "duplicate": ( "An account already exists", "Sign in instead or use a different email address.", ), "pending": ( "Verification is pending", "Enter the code from your most recent local Capterra message.", ), "rate-limited": ( "Too many attempts", "Wait a moment before trying again.", ), "challenge": ( "Enter your verification code", "Use the six-character code from local Capterra messages.", ), "locked": ( "Verification temporarily locked", "Try again later or request a new code.", ), "stale": ( "This code has expired", "Request a new code to continue.", ), "verified": ( "Email verified", "Your account is ready.", ), "authenticated": ( "You’re signed in", "Your account is ready to use.", ), "active": ( "You’re signed in", "You can continue using your Capterra account.", ), "revoked": ( "You’re signed out", "Sign in again whenever you’re ready.", ), "generic-response": ( "Check local Capterra messages", "The same response is shown regardless of whether the account exists.", ), "complete": ( "Password updated", "You can now sign in with your new password.", ), "messages": ( "You have new messages", "Your latest account messages appear below.", ), "empty": ( "Your inbox is empty", "New account messages will appear here.", ), "local-only": ( "Message ready", "Open the message to continue.", ), "smtp-pending": ( "Sending message", "Your message is being prepared.", ), "smtp-sent": ( "Loopback delivery accepted", "This state does not claim that an external email was delivered.", ), "smtp-failed": ( "Message not sent", "Try again in a moment.", ), "selection-empty": ( "Choose software to compare", "Select at least two products to begin.", ), "comparison-ready": ( "Your comparison is ready", "Review the selected products side by side.", ), "invalid-selection": ( "That comparison cannot be created", "Choose two different products and try again.", ), "retry-selection": ( "Try your selection again", "The workspace remains available after the validation failure.", ), "cleared-aftercare": ( "Comparison cleared", "Choose products to start a new comparison.", ), "absent": ( "Notion is not in your favorites", "Save it to find it quickly later.", ), "present": ( "Notion is in your favorites", "You can compare or remove it at any time.", ), "removed": ( "Notion was removed", "It is no longer in your favorites.", ), } REVIEW_AUTHORS = ( ("Ankith T.", "Software Developer", "Information Technology and Services"), ("Jean O.", "Marketing Assistant", "Marketing and Advertising"), ("Maya C.", "Product Manager", "Computer Software"), ("Verified Reviewer", "Senior Lead Consultant", "Insurance"), ("Pupp R.", "Owner", "Events Services"), ("Derrick H.", "Operations Director", "Nonprofit Organization Management"), ("Priya S.", "Research Coordinator", "Higher Education"), ("Noah W.", "Creative Director", "Design"), ("Sofia L.", "People Operations Manager", "Human Resources"), ("Ethan B.", "Founder", "Professional Services"), ) REVIEW_TITLES = ( "One place for notes, tasks, and team work", "Flexible enough for the way our team actually works", "Powerful workspace with a real learning curve", "A dependable home for projects and documentation", "Our shared knowledge base finally stays current", ) REVIEW_OVERALL = ( "Notion has become the place our team checks first. Pages, project " "updates, meeting notes, and decisions stay connected without forcing " "every group into exactly the same workflow.", "The product is capable and pleasantly adaptable once the initial " "workspace structure is in place. It has reduced duplicate documents " "and made handoffs much easier to follow.", "We use it every day for planning and reference material. Larger pages " "can take a moment to load, but the benefit of keeping related work in " "one searchable space outweighs that inconvenience.", ) REVIEW_PROS = ( "Linked databases and reusable templates make recurring work easy to " "standardize without losing flexibility.", "Collaboration, comments, and a clear page history keep distributed " "teams aligned.", "Notes, tasks, and documentation can live together instead of being " "split across several tools.", ) REVIEW_CONS = ( "New teammates need guidance because the number of possible layouts can " "feel overwhelming at first.", "Very large pages and databases occasionally feel slower on mobile.", "Permissions require care when a workspace grows across several teams.", ) # Current anonymous public-template families observed through the 2026-08-02 # Browserbase source freeze. These are presentation records only: every link # stays within this site and every consequential vendor/email action remains # behind the existing honest boundary controls. PUBLIC_PAGE_DATA: dict[str, dict[str, object]] = { "categories-index": { "title": "Browse Our Software Categories", "eyebrow": "Software categories", "lede": "Explore business software by category and find products that fit the way your team works.", "cards": [ ("Accounting", "Track finances, billing, expenses, and reporting."), ("Project Management", "Plan projects, coordinate work, and meet deadlines."), ("Human Resources", "Support recruiting, people operations, and engagement."), ("Customer Relationship Management", "Manage sales relationships and customer activity."), ("Construction Management", "Coordinate jobs, crews, estimates, and field work."), ("Marketing", "Reach customers and measure campaign performance."), ("Customer Service", "Resolve requests and support customers across channels."), ("IT Management", "Operate devices, services, security, and infrastructure."), ], "sections": [("Popular Categories", "Browse the categories software buyers visit most often.")], }, "category-directory": { "title": "Best Accounting Software", "eyebrow": "Accounting software", "lede": "Compare accounting tools using ratings, reviews, features, and practical buying guidance.", "cards": [ ("NetSuite", "Cloud financial management for growing organizations."), ("Xero", "Accounting, invoicing, bank reconciliation, and reporting."), ("Sage Intacct", "Financial management with automation and dimensional reporting."), ("Accounting Seed", "Accounting workflows built for connected business operations."), ("SBS Financials", "Financial reporting and accounting management."), ("Zoho Books", "Online accounting for invoices, expenses, and taxes."), ], "sections": [ ("How to choose accounting software", "Start with the workflows you need, then compare ease of use, support, integrations, and total cost."), ("Accounting software buyers guide", "Use verified reviews and feature comparisons to build a confident shortlist."), ], "filters": ["Business size", "Pricing options", "Features", "Deployment", "User rating"], }, "subcategory-directory": { "title": "Best Free Accounting Software in 2025", "eyebrow": "Free accounting software", "lede": "Review free and free-trial accounting options before choosing the right fit for your business.", "cards": [ ("Ramp", "Expense automation with finance controls."), ("Wave", "Invoicing and accounting for small businesses."), ("Zoho Books", "Bookkeeping, billing, and expense tracking."), ("ProfitBooks", "Simple accounting and inventory workflows."), ("Odoo", "Modular business tools with accounting capabilities."), ("Xero", "Cloud accounting and bank reconciliation."), ("FreshBooks", "Invoices, expenses, time tracking, and reports."), ("QuickBooks Online", "Connected bookkeeping and business reporting."), ], "sections": [ ("10 best free or free trial accounting software", "Compare available plans, core features, and upgrade paths."), ("How we picked the software on this list", "Products are organized around relevance, ratings, and the needs of accounting software buyers."), ], "filters": ["Free plan", "Free trial", "Business size", "Features"], }, "product-alternatives": { "title": "Alternatives to Notion", "eyebrow": "Notion alternatives", "lede": "Compare highly rated alternatives using reviews, features, and pricing information.", "cards": [ ("monday.com AI Work Platform", "Flexible work management with boards and dashboards."), ("Wrike", "Project planning and collaborative work management."), ("Airtable", "Connected workflows built around flexible data."), ("Connecteam", "Operations and communication for deskless teams."), ("Trello", "Visual task management with boards and cards."), ("Jira", "Issue tracking and project planning for software teams."), ("Asana", "Team projects, goals, and workflow coordination."), ("Todoist", "Straightforward task and project organization."), ], "sections": [("Top Notion Alternatives", "Evaluate the products buyers most often compare with Notion.")], }, "product-pricing": { "title": "Pricing for Notion", "eyebrow": "Notion pricing", "lede": "Review available plans and compare how pricing changes with team needs.", "cards": [ ("Free", "$0 · For individuals organizing personal projects."), ("Plus", "$12 per user, per month · For small teams and growing workspaces."), ("Business", "$24 per user, per month · For companies coordinating multiple teams."), ("Enterprise", "Custom pricing · For advanced controls, security, and support."), ], "sections": [ ("Notion has 4 pricing plans", "Compare plan limits and choose the level that matches your team."), ("Popular alternatives to Notion", "Pricing is only one part of a complete software comparison."), ("How should I be thinking about software pricing?", "Consider implementation, support, integrations, and the cost of switching as well as the subscription."), ], }, "compare-builder": { "title": "Start a comprehensive head to head product comparison", "eyebrow": "Compare software", "lede": "Select products to compare ratings, features, pricing, and verified reviews side by side.", "cards": [ ("Celoxis", "Project portfolio management · 4.5"), ("Smartsheet", "Collaborative work management · 4.5"), ("monday.com AI Work Platform", "Flexible work management · 4.6"), ], "sections": [ ("Popular Comparisons", "Begin with products buyers frequently evaluate together."), ("Compare software easily with Capterra’s comparison tool", "Build a focused list and compare the criteria that matter to your team."), ], "comparison_builder": True, }, "compare-products": { "title": "CustomerHero vs SurveyMonkey Features and Cost Comparison", "eyebrow": "Side-by-side comparison", "lede": "See ratings, pricing, features, and review signals together.", "cards": [ ("CustomerHero", "Survey and customer feedback software."), ("SurveyMonkey", "Online surveys, forms, and feedback analysis."), ], "sections": [ ("Summary", "Compare the products at a glance before reviewing individual features."), ("User reviews", "Verified reviews add practical context to product claims."), ("Features", "Review survey design, distribution, reporting, and collaboration capabilities."), ("Pricing", "Confirm plan limits and current vendor pricing before making a final decision."), ], "comparison_table": True, }, "shortlist": { "title": "2026 Capterra Shortlist for Project Management", "eyebrow": "Capterra Shortlist", "lede": "Get to a better list with verified ratings and reviews.", "cards": [ ("Asana", "Projects, portfolios, goals, and team coordination."), ("Jira", "Planning and issue tracking for technical teams."), ("Notion", "Connected docs, projects, knowledge, and workflows."), ("Trello", "Visual project planning with boards and cards."), ("ClickUp", "Tasks, documents, goals, and reporting."), ("monday.com AI Work Platform", "Configurable work management for teams."), ], "sections": [ ("Our Top 5 Picks 2026 Capterra Shortlist", "Products are positioned using ratings and popularity signals."), ("Explore the Full Project Management Shortlist", "Review the broader selection to find the best fit."), ], }, "our-story": { "title": "The #1 destination to find software", "eyebrow": "About Capterra", "lede": "We connect software buyers with verified reviews, product information, and practical guidance.", "cards": [ ("Software Researchers", "Evaluate markets, products, and buyer needs."), ("Review Moderators", "Support review quality and verification."), ("Content Analysts", "Turn research into useful buying guidance."), ("Software Advisors", "Help buyers clarify priorities and navigate options."), ], "sections": [ ("Get to know the specialists behind your success", "Research, review, content, and advisory teams work together for software buyers."), ("We help software providers find their best customers", "Providers can present products while buyers retain access to independent comparison tools."), ("Contact us", "Choose the destination that best matches your question."), ], }, "resources-index": { "title": "Blog & Research", "eyebrow": "Guides and insights", "lede": "Practical research for choosing, buying, and using business software.", "cards": [ ("Accounting & Finance", "Accounting tools, automation, costs, and financial operations."), ("AI", "Artificial intelligence trends, tools, and adoption guidance."), ("Construction", "Technology for contractors, builders, and field teams."), ("Customer Service & Support", "Service operations, channels, and customer experience."), ("Human Resources", "Recruiting, engagement, payroll, and people operations."), ("Program & Project Management", "Planning, collaboration, delivery, and portfolio management."), ], "sections": [ ("Most Recent", "Read the latest analysis and software buying guidance."), ("Explore Articles by Category", "Browse research by the business problem you are working on."), ], }, "resource-policy-article": { "title": "How Capterra Collects and Verifies Reviews", "eyebrow": "Reviews verification", "lede": "Learn how reviewer identity, content checks, and quality controls support useful reviews.", "sections": [ ("Our process of collecting user reviews", "Reviews come from software users who share their first-hand experiences."), ("Our process of verifying reviews", "Identity and content checks help reviews meet publication guidelines."), ("1. The reviewer’s identity is confirmed", "Reviewers provide information that supports identity verification."), ("2. The review content is verified", "Moderation checks relevance, originality, and compliance."), ("3. Fake reviews are actively combated", "Systems and reviewers look for suspicious patterns and abuse."), ], }, "resources-news": { "title": "Capterra Newsroom", "eyebrow": "Press and company news", "lede": "Company background, announcements, media coverage, and press contacts.", "sections": [ ("About Capterra", "Capterra helps organizations find the right software."), ("Contact us", "Media inquiries can be directed to the press team."), ("Press Releases", "Read recent company announcements."), ("In the News", "See selected media coverage and commentary."), ], }, "legal-content": { "title": "GENERAL USER TERMS", "eyebrow": "Legal", "lede": "These terms explain the rules that apply when using Capterra services.", "sections": [ ("1. Acceptance of terms", "Using the service is subject to the current terms and applicable policies."), ("2. Service information", "Product information and user content are provided to support software research."), ("3. User responsibilities", "Users must provide lawful content and use the service responsibly."), ("4. Intellectual property", "Site content and trademarks remain subject to their respective rights."), ("5. Disclaimers and limitations", "Review the complete terms for applicable limitations and notices."), ], }, "resource-category": { "title": "Accounting & Finance Most Recent Posts", "eyebrow": "Accounting & Finance", "lede": "Advice and research for accounting teams and software buyers.", "cards": [ ("6 Accounting Tasks That Can Be Fully Automated", "Where automation can save time in everyday accounting work."), ("Choose the Best Accounting Software", "Learn from buyers with first-hand product experience."), ("Accounting Software Pricing Report", "Compare costs and understand common pricing models."), ("Benefits of Accounting Software", "Consider the gains and tradeoffs of modern accounting tools."), ], }, "resource-author": { "title": "Articles by David Jani", "eyebrow": "Author", "lede": "Research and practical guidance for business technology buyers.", "cards": [ ("How to Create a Project Plan", "A practical framework for building a useful project plan."), ("Software Implementation Tips", "Habits that support smoother software adoption."), ("Project Management Software With Gantt Charts", "Compare planning tools with visual timelines."), ], }, "resource-editorial-article": { "title": "6 Accounting Tasks That Can Be Fully Automated", "eyebrow": "Accounting automation", "lede": "Automating simple tasks can reap huge returns in accounting.", "sections": [ ("What is accounting automation?", "Automation uses software to complete repeatable finance work with less manual handling."), ("1. Expense management", "Capture expenses, apply policies, and route approvals."), ("2. Payroll management", "Coordinate calculations, schedules, and records."), ("3. Bank reconciliation", "Match transactions and flag exceptions for review."), ("4. Accounts receivable", "Prepare invoices and follow payment status."), ("5. Accounts payable", "Process bills, approvals, and payment workflows."), ("6. Tax compliance and financial reporting", "Organize data and produce consistent reports."), ], }, "resource-research-index": { "title": "Capterra’s Proprietary Data & Research Methodologies", "eyebrow": "Research methodology", "lede": "Understand the sources and methods used to create marketplace research.", "cards": [ ("User-generated reviews", "Verified software-user perspectives."), ("Buyer interactions", "Aggregated signals from software research activity."), ("Market surveys", "Structured research with business decision-makers."), ("Analyst insights", "Interpretation from subject-matter specialists."), ("Vendor-sourced research", "Product details provided by software companies."), ], "sections": [ ("Capterra data sources", "Research draws on several complementary kinds of evidence."), ("Approaches to methodology", "Methods are selected to fit the question and available data."), ("Capterra research types", "Editorial, algorithmic, and marketplace research serve different buyer needs."), ], }, "resource-research-agenda": { "title": "Research Agenda", "eyebrow": "Upcoming research", "lede": "Explore the business technology topics scheduled for upcoming research.", "sections": [ ("Q4 Research Agenda", "Software buying, finance operations, AI adoption, and customer experience."), ("Q1 Research Agenda", "Work management, security, marketing, and people operations."), ("Q2 Research Agenda", "Industry technology, analytics, service, and growth priorities."), ], }, "not-found": { "title": "Page not found", "eyebrow": "404", "lede": "The page you were looking for doesn’t exist.", "sections": [("Keep exploring", "Browse software categories, compare products, or return to the home page.")], "not_found": True, }, } templates = Jinja2Templates(directory=str(ROOT / "frontend" / "templates")) templates.env.globals["public_registration_enabled"] = ( PUBLIC_REGISTRATION_VERIFICATION is not None ) def seed_auth_fixtures(auth_store: LocalAuthStore) -> None: auth_store.seed_account( subject_id=PRIMARY_ACCOUNT_SLUG, email=backend_db.PRIMARY_ACCOUNT[2], display_name=backend_db.PRIMARY_ACCOUNT[1], password="CapterraPass123!", ) auth_store.seed_account( subject_id=SECONDARY_ACCOUNT_SLUG, email=backend_db.SECONDARY_ACCOUNT[2], display_name=backend_db.SECONDARY_ACCOUNT[1], password="CapterraPass456!", ) def auth_seed_accounts() -> list[dict[str, object]]: return [ { "subject_id": PRIMARY_ACCOUNT_SLUG, "email": backend_db.PRIMARY_ACCOUNT[2], "display_name": backend_db.PRIMARY_ACCOUNT[1], "password": "CapterraPass123!", }, { "subject_id": SECONDARY_ACCOUNT_SLUG, "email": backend_db.SECONDARY_ACCOUNT[2], "display_name": backend_db.SECONDARY_ACCOUNT[1], "password": "CapterraPass456!", }, ] def configured_mail_runtime() -> dict[str, object]: """Resolve one fail-closed, literal-loopback-only delivery boundary.""" local_only: dict[str, object] = { "mode": MAIL_LOCAL_ONLY, "worker_token": None, "host": None, "port": None, "path": None, } mail_mode = ( os.environ.get("WEBSITEBENCH_LOCAL_MAIL_MODE", "") or os.environ.get("CLAWBENCH_LOCAL_MAIL_MODE", "") ) if mail_mode != MAIL_SMTP_PENDING: return local_only worker_token = ( os.environ.get("WEBSITEBENCH_LOCAL_MAIL_WORKER_TOKEN", "") or os.environ.get("CLAWBENCH_LOCAL_MAIL_WORKER_TOKEN", "") ) raw_url = ( os.environ.get("WEBSITEBENCH_LOCAL_MAIL_LOOPBACK_URL", "") or os.environ.get("CLAWBENCH_LOCAL_MAIL_LOOPBACK_URL", "") ) if len(worker_token) < 20: return local_only try: parsed = urlsplit(raw_url) host = parsed.hostname port = parsed.port address = ipaddress.ip_address(host or "") except (ValueError, TypeError): return local_only if ( parsed.scheme != "http" or not address.is_loopback or parsed.username is not None or parsed.password is not None or port is None or not 1024 <= port <= 65535 or parsed.path not in { "/__websitebench/mail-sink", "/__clawbench/mail-sink", } or parsed.query or parsed.fragment ): return local_only return { "mode": MAIL_SMTP_PENDING, "worker_token": worker_token, "host": str(address), "port": port, "path": parsed.path, } @asynccontextmanager async def lifespan(app: FastAPI): mail_runtime = configured_mail_runtime() site_backend, auth_store = open_site_services( mail_mode=str(mail_runtime["mode"]), mail_worker_token=( str(mail_runtime["worker_token"]) if mail_runtime["worker_token"] is not None else None ), database_path=( backend_db.resolve_data_dir(None, ROOT) / backend_db.DB_FILENAME ), ) if site_backend.config.site_id != SITE_ID: raise RuntimeError("Capterra backend runtime identity is inconsistent") if site_backend.session_cookie["name"] != AUTH_SESSION_COOKIE: raise RuntimeError("Capterra session cookie differs from runtime") database = backend_db.Database( site_backend.lifecycle.database_path.parent ) if database.path != site_backend.lifecycle.database_path: raise RuntimeError("Capterra database path differs from runtime") database.prepare() seed_auth_fixtures(auth_store) auth_store.reconcile_mail( worker_token=( str(mail_runtime["worker_token"]) if mail_runtime["mode"] == MAIL_SMTP_PENDING else None ) ) app.state.site_backend = site_backend app.state.db = database app.state.auth = auth_store app.state.mail_runtime = mail_runtime app.state.mail_delivery_ledger = [] # The public eBook form is an acknowledgement-only boundary. Keep only a # bounded digest set for idempotency; raw addresses are never persisted, # logged, or passed to a mail adapter. app.state.ebook_request_digests = set() try: yield finally: database.close() app = FastAPI( title="Capterra R3 persistent backend", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan, ) @app.get("/static/auth-verification.js", include_in_schema=False) async def public_registration_verification_script() -> Response: return registration_script_response(PUBLIC_REGISTRATION_VERIFICATION) @app.get("/favicon.ico", include_in_schema=False) async def public_favicon() -> FileResponse: """Serve the frozen local brand icon referenced by source replays.""" return FileResponse( ROOT / "static/assets/source-current/2026-07-25/shared/" "capterra-www-favicon.png", media_type="image/png", ) app.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static") @app.middleware("http") async def runtime_headers(request: Request, call_next): response = await call_next(request) style_policy = "style-src 'self'" if response.headers.get("X-WebsiteBench-Replay"): # Frozen source DOM contains inline layout declarations. The builder # removes all source scripts and remote URLs before these read-only # pages are eligible for this narrowly scoped style exception. style_policy += " 'unsafe-inline'" response.headers["Content-Security-Policy"] = ( f"default-src 'self'; img-src 'self' data:; {style_policy}; " "script-src 'self'; connect-src 'self'; font-src 'self'; " "object-src 'none'; frame-ancestors 'none'; base-uri '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 def get_db(request: Request): return request.app.state.db def get_auth(request: Request) -> LocalAuthStore: return request.app.state.auth # Route families that keep the framework's JSON error shape on 404: admin and # worker boundaries, JSON APIs, fixtures, legacy /local POST aliases, and # static assets. Every other unmatched path gets the styled not-found replay. JSON_404_PREFIXES = ( "/__admin", "/__worker", "/api/", "/fixture", "/local/", "/static/", ) @app.exception_handler(StarletteHTTPException) async def styled_http_error( request: Request, exc: StarletteHTTPException ) -> Response: if exc.status_code == 404 and not request.url.path.startswith( JSON_404_PREFIXES ): return render_public_replay("not-found", status_code=404) return JSONResponse( {"detail": exc.detail if exc.detail else "Not Found"}, status_code=exc.status_code, headers=getattr(exc, "headers", None), ) def dispatch_next_mail(app_instance: FastAPI) -> dict[str, object] | None: """Run one worker-authorized, no-redirect loopback dispatch. Public requests may create, queue, retry, and observe mail. Only the private worker boundary calls this function and can reach the target. """ runtime = app_instance.state.mail_runtime if runtime["mode"] != MAIL_SMTP_PENDING: return None worker_token = str(runtime["worker_token"]) auth_store: LocalAuthStore = app_instance.state.auth claim = auth_store.claim_pending_mail( worker_token=worker_token, ) if claim is None: return None mail_id = int(claim["mail_id"]) claim_token = str(claim["claim_token"]) request_id = str(claim["request_id"]) purpose = str(claim["purpose"]) target_request_count = 0 accepted_request_count = 0 response_status: int | None = None receipt_request_id: str | None = None receipt_accepted_effect_count: str | None = None error: str | None = None connection: http.client.HTTPConnection | None = None try: body = json.dumps( { "request_id": request_id, "purpose": purpose, "recipient": str(claim["recipient"]), "template": str(claim["template"]), "verification_code": str(claim["verification_code"]), }, sort_keys=True, separators=(",", ":"), ).encode("utf-8") connection = http.client.HTTPConnection( str(runtime["host"]), int(runtime["port"]), timeout=2.0, ) auth_store.reserve_mail_target_request( mail_id, claim_token, worker_token=worker_token, ) target_request_count = 1 connection.request( "POST", str(runtime["path"]), body=body, headers={ "Content-Type": "application/json", "Content-Length": str(len(body)), "Idempotency-Key": request_id, }, ) response = connection.getresponse() response_status = int(response.status) receipt_request_id = response.getheader( "X-Clawbench-Mail-Request-Id" ) receipt_accepted_effect_count = response.getheader( "X-Clawbench-Mail-Accepted-Effect-Count" ) response.read(4096) if response_status != 202: error = f"loopback sink refused with HTTP {response_status}" elif ( receipt_request_id != request_id or receipt_accepted_effect_count != "1" ): error = "loopback sink acceptance receipt is invalid" else: accepted_request_count = 1 except (OSError, http.client.HTTPException, ValueError): error = MAIL_OUTCOME_UNKNOWN finally: if connection is not None: connection.close() auth_store.finish_mail_claim( mail_id, claim_token, sent=accepted_request_count == 1, target_request_count=target_request_count, accepted_request_count=accepted_request_count, error=error, worker_token=worker_token, ) with auth_store.connect() as connection: durable_row = connection.execute( "SELECT delivery_state_version,target_request_count," "accepted_effect_count,status FROM local_auth_mail_outbox " "WHERE mail_id=? AND session_digest=? AND purpose=?", (mail_id, claim["session_digest"], purpose), ).fetchone() if durable_row is None: raise RuntimeError("worker delivery lost its durable outbox row") event = { "request_id": request_id, "mail_id": mail_id, "purpose": purpose, "delivery_attempts": int(claim["delivery_attempts"]), "target": "literal-loopback", "target_request_count": target_request_count, "accepted_request_count": accepted_request_count, "response_status": response_status, "receipt_request_id": receipt_request_id, "receipt_accepted_effect_count": receipt_accepted_effect_count, "delivery_state_version": int( durable_row["delivery_state_version"] ), "durable_target_request_count": int( durable_row["target_request_count"] ), "durable_accepted_effect_count": int( durable_row["accepted_effect_count"] ), "status": str(durable_row["status"]), "production_request_count": 0, "production_effect_count": 0, } app_instance.state.mail_delivery_ledger.append(event) return event def auth_csrf(session_token: str) -> str: return hmac.new( backend_db.session_secret(), f"auth-csrf:{session_token}".encode("utf-8"), hashlib.sha256, ).hexdigest() def comparison_owner_id(request: Request, session_token: str) -> str: """Bind anonymous comparison state to one opaque server session.""" return get_auth(request).session_owner_digest(session_token) def ensure_auth_session( request: Request, ) -> tuple[str, dict[str, object], bool]: existing = request.cookies.get(AUTH_SESSION_COOKIE) token, session = get_auth(request).ensure_session(existing) return token, session, token != existing def set_auth_cookie(response: HTMLResponse | RedirectResponse, token: str) -> None: cookie = dict(SITE_BACKEND_RUNTIME.cookie_options) response.set_cookie( AUTH_SESSION_COOKIE, token, httponly=bool(cookie["httponly"]), samesite=str(cookie["samesite"]), secure=bool(cookie["secure"]), path=str(cookie["path"]), max_age=30 * 24 * 60 * 60, ) def valid_auth_csrf(values: dict[str, str], token: str) -> bool: supplied = values.get("csrf", "") return bool(supplied) and secrets.compare_digest( supplied, auth_csrf(token) ) def admin_boundary_authorized(request: Request) -> bool: """Require both injected secret authority and a distinct admin origin.""" expected_token = backend_db.admin_token() expected_host = backend_db.admin_host() request_host = request.headers.get("host", "").rsplit(":", 1)[0].casefold() supplied_token = ( request.headers.get(ADMIN_TOKEN_HEADER, "") or request.headers.get(LEGACY_ADMIN_TOKEN_HEADER, "") ) return bool(expected_token and expected_host) and secrets.compare_digest( supplied_token, expected_token ) and secrets.compare_digest(request_host, expected_host) def fixture_boundary_authorized(request: Request) -> bool: del request return backend_db.test_fixtures_enabled() def current_account(request: Request): """Resolve only opaque auth in public; legacy sessions are test-only.""" session = get_auth(request).resolve_session( request.cookies.get(AUTH_SESSION_COOKIE) ) if session and session.get("authenticated"): auth_account = session.get("account") if isinstance(auth_account, dict): subject_id = auth_account.get("subject_id") if isinstance(subject_id, str): account = get_db(request).account_by_slug(subject_id) if account is not None: return account if backend_db.test_fixtures_enabled(): return get_db(request).account_for_cookie( request.cookies.get(SESSION_COOKIE) ) return None def review_form_boundary(request: Request) -> tuple[str, str]: """Resolve the review submit surface and its anti-forgery token. Public review mutations are always bound to the opaque server session. The fixed token survives only on the explicitly test-only fixture route. """ token = request.cookies.get(AUTH_SESSION_COOKIE, "") session = get_auth(request).resolve_session(token) if session and session.get("authenticated"): return "/local/reviews/notion", auth_csrf(token) if backend_db.test_fixtures_enabled() and get_db(request).account_for_cookie( request.cookies.get(SESSION_COOKIE) ): return "/fixture/reviews/notion", CSRF_VALUE return "/local/reviews/notion", "" def fixture_context(request: Request, **values: object) -> dict[str, object]: account = current_account(request) opaque_session = request.cookies.get(AUTH_SESSION_COOKIE) reviewer_name = account["display_name"] if account else "Alex Green" reviewer_initials = "".join( part[0].upper() for part in reviewer_name.split() if part )[:2] context: dict[str, object] = { "request": request, "site_id": SITE_ID, "version": VERSION, "fixture_id": FIXTURE_ID, "frozen_clock": FROZEN_CLOCK, "product_id": PRODUCT_ID, "product_name": PRODUCT_NAME, "receipt_id": RECEIPT_ID, # Size and average of the local review corpus. Every template that # quotes a review count uses these, so no page can advertise a review # total this edition does not actually hold. "local_review_total": LOCAL_REVIEW_TOTAL, "local_review_average": LOCAL_REVIEW_AVERAGE, "signed_in": account is not None, "reviewer_name": reviewer_name, "reviewer_initials": reviewer_initials, "reviewer_email": ( account["email"] if account else "alex.green@example.test" ), "fixture_accounts": [ { "slug": backend_db.PRIMARY_ACCOUNT[0], "display_name": backend_db.PRIMARY_ACCOUNT[1], "email": backend_db.PRIMARY_ACCOUNT[2], "initials": "AG", "purpose": "primary review fixture", }, { "slug": backend_db.SECONDARY_ACCOUNT[0], "display_name": backend_db.SECONDARY_ACCOUNT[1], "email": backend_db.SECONDARY_ACCOUNT[2], "initials": "JL", "purpose": "cross-account boundary probe", }, ], "current_path": request.url.path, "assets_base": ASSETS_BASE, "csrf": CSRF_VALUE, "auth_csrf": ( auth_csrf(opaque_session) if opaque_session and get_auth(request).resolve_session(opaque_session) is not None else None ), } context.update(values) return context def exact_effect_coverage_id( route_id: str, affordance: dict[str, object], assertion: dict[str, object], ) -> str: """Return the immutable R1 coverage identity for one denied effect.""" def coverage_slug(value: object) -> str: normalized = re.sub( r"[^a-z0-9]+", "-", str(value).lower() ).strip("-") return normalized or "control" return ".".join( ( "exact", str(affordance["control_identity"]), coverage_slug(assertion["id"]), coverage_slug(route_id), coverage_slug(affordance["state_ids"][0]), coverage_slug(affordance["role_ids"][0]), coverage_slug(affordance["variant_ids"][0]), coverage_slug(affordance["viewports"][0]), ) ) def scope_effect_affordances( route_id: str | None, state_ids: tuple[str, ...] | list[str] | None, role_ids: tuple[str, ...] | list[str] | None = None, ) -> list[dict[str, object]]: """Materialize every applicable source-visible external-action boundary.""" if not route_id or route_id not in SCOPE_ROUTES: return [] applicable_states = set(state_ids or []) applicable_roles = set(role_ids or []) rows: list[dict[str, object]] = [] route = SCOPE_ROUTES[route_id] for affordance in route.get("affordances", []): assertions = affordance.get("effect_assertions", []) if not assertions: continue row_states = set(affordance.get("state_ids", [])) if applicable_states and not (row_states & applicable_states): continue row_roles = set(affordance.get("role_ids", [])) if applicable_roles and not (row_roles & applicable_roles): continue rendered_assertions = [ { "id": str(assertion["id"]), "observable_effect": str(assertion["observable_effect"]), "required_truth": str(assertion["required_truth"]), "coverage_id": exact_effect_coverage_id( route_id, affordance, assertion ), } for assertion in assertions ] rows.append( { "id": str(affordance["id"]), "control_identity": str(affordance["control_identity"]), "label": str(affordance["label"]), "semantic_destination": str( affordance["semantic_destination"] ), "viewport": str(affordance["viewports"][0]), "state_id": str(affordance["state_ids"][0]), "effect_payload": json.dumps( rendered_assertions, ensure_ascii=False, separators=(",", ":"), ), } ) return rows REVIEW_TENURES = ("6-12 months", "1-2 years", "2+ years") REVIEW_COMPANY_SIZES = ("1-10", "11-50", "51-200", "201-500", "501+") REVIEW_FREQUENCIES = ("daily", "weekly", "monthly") REVIEW_DATES = ( ("July 19, 2026", "2026-07-19"), ("June 30, 2026", "2026-06-30"), ("June 12, 2026", "2026-06-12"), ("May 3, 2026", "2026-05-03"), ("April 22, 2026", "2026-04-22"), ) # Query value -> the card field value it selects. LENGTH_OF_USE_VALUES = {"1-2-years": "1-2 years"} REVIEW_AVATARS = ( "notion-reviews/authorship-reviewer-1.jpg", "notion-reviews/authorship-reviewer-2.jpg", "notion-profile/placeholder-user.jpg", ) def build_review_corpus() -> list[dict[str, object]]: """Build the whole deterministic local review set, independent of paging. These reviews are openly local test data, not captured remote reviews. Every displayed attribute is generated here, which is exactly why each filter control can select on one: company size and frequency of use are generated alongside rating and tenure rather than being rendered as controls with nothing behind them. """ cards: list[dict[str, object]] = [] for index in range(REVIEW_PAGE_SIZE * REVIEW_PAGE_COUNT): author, role, industry = REVIEW_AUTHORS[index % len(REVIEW_AUTHORS)] rating = (5, 4, 5, 3, 4)[index % 5] date_label, date_sort = REVIEW_DATES[index % len(REVIEW_DATES)] cards.append( { "author": author, "role": role, "industry": industry, # Mixed radix: 5 ratings x 3 tenures x 5 company sizes x 3 # frequencies is exactly the 225-review corpus, so each # combination occurs and no two attributes are locked together. # Deriving two filters from one modulus would make some filter # combinations unsatisfiable for reasons that are an artefact of # generation rather than anything about the data. "tenure": REVIEW_TENURES[(index // 5) % len(REVIEW_TENURES)], "company_size": REVIEW_COMPANY_SIZES[ (index // 15) % len(REVIEW_COMPANY_SIZES) ], "frequency": REVIEW_FREQUENCIES[ (index // 75) % len(REVIEW_FREQUENCIES) ], "title": REVIEW_TITLES[index % len(REVIEW_TITLES)], "rating": rating, "rating_class": f"rating-{rating}", "date": date_label, "date_sort": date_sort, "overall": REVIEW_OVERALL[index % len(REVIEW_OVERALL)], "pros": REVIEW_PROS[index % len(REVIEW_PROS)], "cons": REVIEW_CONS[index % len(REVIEW_CONS)], "avatar": REVIEW_AVATARS[index % len(REVIEW_AVATARS)], "local_number": index + 1, } ) return cards REVIEW_CORPUS = build_review_corpus() LOCAL_REVIEW_TOTAL = len(REVIEW_CORPUS) LOCAL_REVIEW_AVERAGE = round( sum(int(card["rating"]) for card in REVIEW_CORPUS) / LOCAL_REVIEW_TOTAL, 1 ) # Product-neutral review copy for the catalog products. Same honesty rule as # the corpus above: openly local test data, never captured remote reviews. GENERIC_REVIEW_TITLES = ( "Does the job our team needed", "Solid choice after comparing several options", "Capable product with a few rough edges", "Reliable day to day once configured", "Good value for the way we work", ) GENERIC_REVIEW_OVERALL = ( "{name} has settled into our daily routine. Setup took some planning, " "but the core workflows are dependable and the team rarely needs help.", "We evaluated a few competitors before choosing {name}. The deciding " "factors were the clean interface and how quickly new teammates became " "productive.", "{name} covers the essentials well. Some advanced options take time to " "discover, but the documentation filled the gaps for us.", ) GENERIC_REVIEW_PROS = ( "Straightforward onboarding and a layout that keeps everyday actions " "easy to find.", "Dependable performance, and updates have not disrupted our setup.", "Flexible configuration that adapted to our process instead of forcing " "a new one.", ) GENERIC_REVIEW_CONS = ( "Some settings sit a few menus deep and take time to locate.", "Reporting covers the basics but larger exports can feel slow.", "The pricing tiers took a careful read to match to our team size.", ) def _generic_rating_sequence(count: int, rating_tenths: int) -> list[int]: """A rating multiset whose mean rounds to the displayed product rating.""" low = min(5, max(1, rating_tenths // 10)) extra = 0 if low < 5: extra = round(count * (rating_tenths - low * 10) / 10) extra = min(max(extra, 0), count) ratings = [low + 1] * extra + [low] * (count - extra) # Mean-preserving spread: swap a (low, low+1) pair for (low-1, low+2) # occasionally so the histogram is not just two adjacent bars. for start in range(0, count - 40, 40): end = count - 1 - start if ( low >= 2 and low + 2 <= 5 and ratings[start] == low + 1 and ratings[end] == low ): ratings[start], ratings[end] = low + 2, low - 1 # Interleave from both ends so pages mix ratings instead of clustering. ordered: list[int] = [] front, back = 0, count - 1 while front <= back: ordered.append(ratings[front]) if front != back: ordered.append(ratings[back]) front += 1 back -= 1 return ordered @functools.lru_cache(maxsize=256) def review_corpus_for( product_id: str, product_name: str, rating_tenths: int, count: int, ) -> list[dict[str, object]]: """The deterministic local review corpus for one catalog product. Notion keeps the original 225-review corpus byte for byte; every other product gets a corpus seeded on its id, sized to the local review count the catalog advertises for it, with a mean matching its displayed rating. """ if product_id == backend_db.PRODUCT_ID: return REVIEW_CORPUS base = int( hashlib.sha256( f"capterra-review-corpus:{product_id}".encode("utf-8") ).hexdigest()[:8], 16, ) ratings = _generic_rating_sequence(count, rating_tenths) cards: list[dict[str, object]] = [] for index in range(count): author, role, industry = REVIEW_AUTHORS[(index + base) % len(REVIEW_AUTHORS)] rating = ratings[index] date_label, date_sort = REVIEW_DATES[(index + base) % len(REVIEW_DATES)] cards.append( { "author": author, "role": role, "industry": industry, # Small co-prime radices so every tenure/size/frequency value # (and therefore every filter control) is satisfiable even for # the smallest 25-review corpora. "tenure": REVIEW_TENURES[index % len(REVIEW_TENURES)], "company_size": REVIEW_COMPANY_SIZES[ (index // 3) % len(REVIEW_COMPANY_SIZES) ], "frequency": REVIEW_FREQUENCIES[ (index // 5) % len(REVIEW_FREQUENCIES) ], "title": GENERIC_REVIEW_TITLES[ (index + base) % len(GENERIC_REVIEW_TITLES) ], "rating": rating, "rating_class": f"rating-{rating}", "date": date_label, "date_sort": date_sort, "overall": GENERIC_REVIEW_OVERALL[ (index + base) % len(GENERIC_REVIEW_OVERALL) ].format(name=product_name), "pros": GENERIC_REVIEW_PROS[ (index + base) % len(GENERIC_REVIEW_PROS) ], "cons": GENERIC_REVIEW_CONS[ (index + base) % len(GENERIC_REVIEW_CONS) ], "avatar": REVIEW_AVATARS[(index + base) % len(REVIEW_AVATARS)], "local_number": index + 1, } ) return cards def product_review_corpus(product: Mapping[str, object]) -> list[dict[str, object]]: return review_corpus_for( str(product["id"]), str(product["name"]), int(round(float(product["rating"] or 4.2) * 10)), int(product["local_review_count"] or 25), ) def profile_sub_ratings(product: Mapping[str, object]) -> dict[str, float]: """Captured sub-ratings when the card carried them, else seeded near the overall rating (and labelled derived by the catalog's derived_fields).""" captured = product.get("sub_ratings") or {} rating = float(product.get("rating") or 4.2) base = int( hashlib.sha256( f"capterra-sub-ratings:{product['id']}".encode("utf-8") ).hexdigest()[:8], 16, ) def near(shift: int) -> float: return max(1.0, min(5.0, round(rating + ((base >> shift) % 5 - 2) / 10, 1))) return { "overall": captured.get("overall", round(rating, 1)), "ease_of_use": captured.get("ease_of_use", near(0)), "customer_service": captured.get("customer_service", near(3)), "features": captured.get("features", near(6)), "value_for_money": captured.get("value_for_money", near(9)), } def select_reviews( filter_values: Mapping[str, str] | None = None, corpus: list[dict[str, object]] | None = None, ) -> list[dict[str, object]]: """Apply the review filter controls to the local corpus.""" rows = list(REVIEW_CORPUS if corpus is None else corpus) if not filter_values: return rows rating = filter_values.get("rating", "all") if rating != "all": rows = [row for row in rows if str(row["rating"]) == rating] company_size = filter_values.get("company_size", "all") if company_size != "all": rows = [row for row in rows if row["company_size"] == company_size] role = filter_values.get("role", "all") if role != "all": # The control offers "Manager"; reviewer roles are job titles, so match # any title carrying that word (Product Manager, People Ops Manager...). rows = [row for row in rows if role in str(row["role"]).casefold()] length_of_use = filter_values.get("length_of_use", "all") if length_of_use != "all": wanted = LENGTH_OF_USE_VALUES.get(length_of_use) rows = [row for row in rows if row["tenure"] == wanted] frequency = filter_values.get("frequency", "all") if frequency != "all": rows = [row for row in rows if row["frequency"] == frequency] if filter_values.get("sort") == "newest": rows.sort(key=lambda row: str(row["date_sort"]), reverse=True) return rows def review_cards( page: int, filter_values: Mapping[str, str] | None = None, corpus: list[dict[str, object]] | None = None, ) -> list[dict[str, object]]: """One page of reviews, after the active filters have been applied.""" rows = select_reviews(filter_values, corpus) start = (page - 1) * REVIEW_PAGE_SIZE return rows[start : start + REVIEW_PAGE_SIZE] def render( request: Request, template: str, *, status_code: int = 200, **values: object, ) -> HTMLResponse: return templates.TemplateResponse( request=request, name=template, context=fixture_context(request, **values), status_code=status_code, ) def render_public_template( request: Request, template_id: str, *, status_code: int = 200, ) -> HTMLResponse: """Render one hash-bound anonymous source-template family.""" page = dict(PUBLIC_PAGE_DATA[template_id]) page["template_id"] = template_id return render( request, "public_template.html", status_code=status_code, page_title=str(page["title"]), body_class=f"public-template-page template-{template_id}", page=page, ) def render_public_replay( page_id: str, *, status_code: int = 200, ) -> HTMLResponse: """Serve one source-derived, script-stripped public template offline.""" if not re.fullmatch(r"[a-z0-9-]+", page_id): raise RuntimeError("invalid public replay page id") page_path = PUBLIC_REPLAY_ROOT / f"{page_id}.html" if not page_path.is_file(): raise RuntimeError(f"missing public replay page: {page_id}") return HTMLResponse( page_path.read_text(encoding="utf-8"), status_code=status_code, headers={"X-WebsiteBench-Replay": page_id}, ) 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 normalize_review_text(value: str) -> tuple[str, list[str]]: """Return the canonical local review text and finite validation errors.""" normalized = unicodedata.normalize( "NFC", value.replace("\r\n", "\n").replace("\r", "\n") ).strip() errors: list[str] = [] if not normalized: errors.append("Review text is required.") return normalized, errors if len(normalized) > REVIEW_TEXT_MAX_CODEPOINTS: errors.append( "Review text must be 2,000 Unicode code points or fewer." ) if any( unicodedata.category(character) in {"Cc", "Cf"} and character not in {"\n", "\t"} for character in normalized ): errors.append( "Review text cannot contain control or format characters; " "tabs and line breaks are allowed." ) return normalized, errors SAFE_NEXT_PATHS = frozenset( { "/", "/compare", f"/favorites/software/{PRODUCT_ID}", "/reviews/notion/write", "/reviews/search/", "/p/186596/Notion/", "/p/186596/Notion/reviews/", "/workspace/", "/workspace/saved/products/", "/workspace/profile/", } ) LEGACY_NEXT_PATHS = { "/local/software/comparison": "/compare", "/local/software/favorites": f"/favorites/software/{PRODUCT_ID}", } # Same-origin catalog surfaces are also safe redirect targets: product pages, # category directories, per-product favorites, and per-product review forms. SAFE_NEXT_RE = re.compile( r"^(?:" r"/p/\d+/[A-Za-z0-9\-]+/(?:reviews/)?" r"|/[a-z0-9][a-z0-9-]*-software/" r"|/favorites/software/[A-Za-z0-9.\-]+" r"|/reviews/[a-z0-9][a-z0-9.\-]*/write" r")$" ) def safe_next(value: str | None) -> str: if value in LEGACY_NEXT_PATHS: return LEGACY_NEXT_PATHS[value] if value in SAFE_NEXT_PATHS: return str(value) if value and SAFE_NEXT_RE.match(value): return str(value) return "/reviews/notion/write" def safe_registration_next(value: str | None) -> str: return safe_next(value) def render_r2_contract_state( request: Request, *, route_id: str, requested_state: str, status_code: int = 200, canonicalize_state: bool = True, **extra: object, ) -> HTMLResponse: """Render one exact frozen R2 route/state without inventing source truth.""" route = SCOPE_ROUTES[route_id] declared_states = [ str(value) for value in route.get("states", []) if isinstance(value, str) ] if not declared_states: raise RuntimeError(f"{route_id} has no frozen states") state = ( requested_state if requested_state in declared_states else declared_states[0] ) state_heading, state_summary = R2_STATE_COPY[state] token, session, created = ensure_auth_session(request) context: dict[str, object] = { "auth_csrf": auth_csrf(token), "auth_session": session, "local_mail": None, "favorite_state": None, "comparison_state": None, "product_options": ( (PRODUCT_ID, "Notion"), ("asana-101", "Asana"), ("monday-102", "monday.com"), ), "comparison_products": ( { "id": PRODUCT_ID, "name": "Notion", "rating": "4.7 / 5", "price": "$12 per user/month", "features": "Docs, wikis, databases, and project work", }, { "id": "asana-101", "name": "Asana", "rating": "4.5 / 5", "price": "$10.99 per user/month", "features": "Projects, goals, portfolios, and workflows", }, { "id": "monday-102", "name": "monday.com", "rating": "4.6 / 5", "price": "$9 per seat/month", "features": "Boards, dashboards, automations, and forms", }, ), } account = current_account(request) if route_id == "auth-local-inbox": purpose = request.query_params.get("purpose", "registration") if purpose not in {"registration", "password-reset"}: purpose = "registration" context["local_mail"] = get_auth(request).local_mail_for_session( token, purpose=purpose ) context["mail_delivery"] = get_auth(request).session_mail_state( token, purpose=purpose ) context["mail_purpose"] = purpose elif account is not None and route_id == "software-favorites": context["favorite_state"] = get_db(request).favorite_state( int(account["id"]) ) elif route_id == "local-comparison": context["comparison_state"] = get_db( request ).anonymous_comparison_state( comparison_owner_id(request, token) ) context.update(extra) canonical_public_route = request.url.path in set(R2_ROUTE_PATHS.values()) if canonicalize_state and request.method == "GET" and ( canonical_public_route or not backend_db.test_fixtures_enabled() ): if route_id == "auth-register": flow = get_auth(request).session_flow_status( token, purpose="registration" ) state = "entry" if flow["state"] == "missing" else "pending" elif route_id == "auth-register-verify": flow = get_auth(request).session_flow_status( token, purpose="registration" ) owner_session_id = get_auth(request).session_owner_digest(token) if get_db(request).has_auth_transition( owner_session_id, "registration-verified" ): state = "verified" else: state = str(flow["state"]) if state not in {"challenge", "locked", "stale"}: state = "stale" elif route_id == "auth-login": state = "authenticated" if account is not None else "entry" elif route_id == "auth-logout": state = "active" if account is not None else "revoked" elif route_id == "auth-password-forgot": flow = get_auth(request).session_flow_status( token, purpose="password-reset" ) state = ( "generic-response" if flow["state"] != "missing" else "entry" ) elif route_id == "auth-password-verify": flow = get_auth(request).session_flow_status( token, purpose="password-reset" ) state = str(flow["state"]) if state not in {"challenge", "locked", "stale", "verified"}: state = "stale" elif route_id == "auth-password-reset": flow = get_auth(request).session_flow_status( token, purpose="password-reset" ) owner_session_id = get_auth(request).session_owner_digest(token) if get_db(request).has_auth_transition( owner_session_id, "password-reset-complete" ): state = "complete" elif flow["state"] == "verified": state = "verified" else: state = "stale" elif route_id == "auth-local-inbox": status = get_auth(request).session_mail_status( token, purpose=str(context.get("mail_purpose", "registration")) ) state = ( status.casefold().replace("_", "-") if status is not None else "empty" ) if ( request.query_params.get("view") == "messages" and context.get("local_mail") is not None ): state = "messages" elif route_id == "software-favorites": favorite = context.get("favorite_state") state = ( "present" if isinstance(favorite, dict) and favorite.get("present") else "removed" if isinstance(favorite, dict) and int(favorite.get("version", 0)) > 0 else "absent" ) elif route_id == "local-comparison": comparison = context.get("comparison_state") state = ( "comparison-ready" if isinstance(comparison, dict) and comparison.get("product_ids") else "cleared-aftercare" if isinstance(comparison, dict) and int(comparison.get("version", 0)) > 0 else "selection-empty" ) state_heading, state_summary = R2_STATE_COPY[state] response = render( request, "r2_contract_state.html", status_code=status_code, page_title=str(R2_ROUTE_UI[route_id]["title"]), route_id=route_id, route_path=R2_ROUTE_PATHS[route_id], route_ui=R2_ROUTE_UI[route_id], state=state, state_heading=state_heading, state_summary=state_summary, declared_states=declared_states, scope_route_id=route_id, scope_state_ids=(state,), **context, ) if created: set_auth_cookie(response, token) return response @app.get("/healthz") async def healthz(request: Request) -> JSONResponse: database = get_db(request) return JSONResponse( { "status": "ok", "ok": True, "site_id": SITE_ID, "stage": "backend", "version": VERSION, "fixture_id": FIXTURE_ID, "frozen_clock": FROZEN_CLOCK, "persistent_backend": True, "db": { "path": str(database.path), "migration_head": database.migration_head(), }, }, headers={ "X-WebsiteBench-Container-Build-ID": os.environ.get( "DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "") ) }, ) @app.post("/__admin/reset") async def admin_reset(request: Request) -> JSONResponse: """Admin-only reset. Never linked from any UI template.""" if not admin_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) database = get_db(request) auth_store = get_auth(request) auth_store.reset_site_state( site_reset=database.reset_in_transaction, seed_accounts=auth_seed_accounts(), ) return JSONResponse( { "ok": True, "reset": True, "reseeded": True, "migration_head": database.migration_head(), "auth_counts": auth_store.counts(), } ) @app.post("/__admin/mail/seed-failed", include_in_schema=False) async def admin_seed_failed_mail(request: Request) -> JSONResponse: """Seed one session-owned failed row for a public retry probe.""" if not admin_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) values = await urlencoded_form(request) purpose = values.get("purpose", "registration") if purpose not in {"registration", "password-reset"}: return JSONResponse({"detail": "Invalid purpose"}, status_code=422) try: delivery_attempts = int(values.get("attempts", "2")) except ValueError: return JSONResponse({"detail": "Invalid attempts"}, status_code=422) if delivery_attempts not in {2, 3}: return JSONResponse({"detail": "Invalid attempts"}, status_code=422) token = request.cookies.get(AUTH_SESSION_COOKIE, "") auth_store = get_auth(request) if auth_store.resolve_session(token) is None: return JSONResponse( {"detail": "Current session has no mail flow"}, status_code=409, ) session_digest = auth_store.session_owner_digest(token) now = int(time.time()) flow_table, flow_id_column = ( ("local_auth_registration_flows", "pending_id") if purpose == "registration" else ("local_auth_password_reset_flows", "reset_id") ) with auth_store.connect() as connection: connection.execute("BEGIN IMMEDIATE") try: changed = connection.execute( "UPDATE local_auth_mail_outbox SET status='SMTP_FAILED'," "is_simulation=0,delivery_attempts=?,claim_token=NULL," "last_error='producer retry probe',attempted_at=?,sent_at=NULL " "WHERE mail_id=(" "SELECT mail_id FROM local_auth_mail_outbox " "WHERE session_digest=? AND purpose=? " "ORDER BY mail_id DESC LIMIT 1" ") AND session_digest=? AND purpose=? " "AND status='LOCAL_ONLY' AND is_simulation=1 " "AND delivery_attempts=0 AND claim_token IS NULL " "AND attempted_at IS NULL AND sent_at IS NULL " f"AND flow_id=(SELECT {flow_id_column} FROM {flow_table} " "WHERE session_digest=? AND verified_at IS NULL " "AND attempts=0 AND expires_at>?)", ( delivery_attempts, now, session_digest, purpose, session_digest, purpose, session_digest, now, ), ).rowcount if changed != 1: connection.rollback() return JSONResponse( {"detail": "Current session has no mail flow"}, status_code=409, ) row = connection.execute( "SELECT mail_id,flow_id,session_digest,status,is_simulation," "delivery_attempts,claim_token,attempted_at,sent_at " "FROM local_auth_mail_outbox " "WHERE session_digest=? AND purpose=? " "ORDER BY mail_id DESC LIMIT 1", (session_digest, purpose), ).fetchone() if ( row is None or str(row["session_digest"]) != session_digest or str(row["status"]) != "SMTP_FAILED" or int(row["is_simulation"]) != 0 or int(row["delivery_attempts"]) != delivery_attempts or row["claim_token"] is not None or row["attempted_at"] != now or row["sent_at"] is not None ): connection.rollback() return JSONResponse( {"detail": "Failed mail setup postcondition failed"}, status_code=409, ) connection.commit() except BaseException: connection.rollback() raise assert row is not None return JSONResponse( { "ok": True, "mail_id": int(row["mail_id"]), "status": str(row["status"]), "delivery_attempts": int(row["delivery_attempts"]), "claim_token": row["claim_token"], "attempted_at": row["attempted_at"], "sent_at": row["sent_at"], } ) @app.post("/__admin/auth/setup", include_in_schema=False) async def admin_auth_setup(request: Request) -> JSONResponse: """Expire one current session-owned flow for a Producer state probe.""" if not admin_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) values = await urlencoded_form(request) scenario = values.get("scenario", "") scenarios = { "registration-expired": ( "local_auth_registration_flows", "pending_id", ), "password-reset-expired": ( "local_auth_password_reset_flows", "reset_id", ), } target = scenarios.get(scenario) if target is None: return JSONResponse({"detail": "Invalid scenario"}, status_code=422) table, flow_id_column = target token = request.cookies.get(AUTH_SESSION_COOKIE, "") auth_store = get_auth(request) if auth_store.resolve_session(token) is None: return JSONResponse( {"detail": "Current session has no auth flow"}, status_code=409, ) session_digest = auth_store.session_owner_digest(token) now = int(time.time()) with auth_store.connect() as connection: connection.execute("BEGIN IMMEDIATE") try: changed = connection.execute( f"UPDATE {table} SET expires_at=?,updated_at=? " "WHERE session_digest=? AND verified_at IS NULL " "AND attempts=0 AND expires_at>?", (now - 1, now, session_digest, now), ).rowcount if changed != 1: connection.rollback() return JSONResponse( {"detail": "Current session has no auth flow"}, status_code=409, ) row = connection.execute( f"SELECT {flow_id_column},session_digest,expires_at,attempts," f"verified_at,updated_at FROM {table} " "WHERE session_digest=?", (session_digest,), ).fetchone() if ( row is None or str(row["session_digest"]) != session_digest or int(row["expires_at"]) > now or int(row["attempts"]) != 0 or row["verified_at"] is not None or int(row["updated_at"]) != now ): connection.rollback() return JSONResponse( {"detail": "Auth setup postcondition failed"}, status_code=409, ) connection.commit() except BaseException: connection.rollback() raise return JSONResponse({"ok": True, "scenario": scenario}) @app.get("/__admin/mail/state", include_in_schema=False) async def admin_mail_state(request: Request) -> JSONResponse: """Read one session-owned mail row for a Producer activation probe.""" if not admin_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) purpose = request.query_params.get("purpose", "registration") if purpose not in {"registration", "password-reset"}: return JSONResponse({"detail": "Invalid purpose"}, status_code=422) token = request.cookies.get(AUTH_SESSION_COOKIE, "") state = get_auth(request).session_mail_state(token, purpose=purpose) if state is None: return JSONResponse( {"detail": "Current session has no mail flow"}, status_code=409, ) return JSONResponse( { "ok": True, "mail_id": int(state["mail_id"]), "status": str(state["status"]), "delivery_attempts": int(state["delivery_attempts"]), "claim_token": state["claim_token"], "attempted_at": state["attempted_at"], "sent_at": state["sent_at"], "retryable": bool(state["retryable"]), } ) @app.post("/__worker/mail/dispatch", include_in_schema=False) async def private_mail_worker_dispatch(request: Request) -> JSONResponse: """Dispatch at most one queued message across the private worker boundary.""" runtime = request.app.state.mail_runtime expected = ( str(runtime["worker_token"]) if runtime["mode"] == MAIL_SMTP_PENDING else "" ) supplied = request.headers.get("X-Clawbench-Mail-Worker-Token", "") if ( not expected or not supplied or not secrets.compare_digest(supplied, expected) ): return JSONResponse({"detail": "Not found"}, status_code=404) event = dispatch_next_mail(request.app) return JSONResponse( { "ok": True, "dispatched": event is not None, "status": event["status"] if event is not None else None, "target_request_count": ( event["target_request_count"] if event is not None else 0 ), "accepted_effect_count": ( event["durable_accepted_effect_count"] if event is not None else 0 ), "production_request_count": 0, "production_effect_count": 0, } ) @app.get( "/__admin/contract-audit/{route_id}", response_class=HTMLResponse, include_in_schema=False, ) async def admin_contract_audit( request: Request, route_id: str, state: str, ) -> Response: if not admin_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) route = SCOPE_ROUTES.get(route_id) if route is None or state not in route.get("states", []): return JSONResponse( {"detail": "Unknown contract route or state"}, status_code=404, ) return render( request, "contract_audit.html", page_title="Contract audit", body_class="contract-audit-page", audit_route_id=route_id, audit_state_id=state, scope_effect_affordances=scope_effect_affordances( route_id, [state], ), ) @app.get("/", response_class=HTMLResponse) async def home(request: Request) -> HTMLResponse: account = current_account(request) if account is None: return render_public_replay("home") return render( request, "home.html", page_title="Find the right software", body_class="home-page", scope_route_id="home", scope_state_ids=( ("authenticated",) if account is not None else ("loaded", "search-focused") ), ) @app.get("/workspace/", response_class=HTMLResponse) async def workspace_dashboard(request: Request) -> HTMLResponse: """Render the source-observed buyer workspace in local account state.""" return render( request, "workspace.html", page_title="My Account", body_class="workspace-page", workspace_view="dashboard", scope_route_id="workspace-dashboard", favorite_state=None, ) @app.get("/workspace/saved/products/", response_class=HTMLResponse) async def workspace_saved_products(request: Request) -> HTMLResponse: account = current_account(request) favorite_state = ( get_db(request).favorite_state(int(account["id"])) if account is not None else None ) saved_products = ( get_db(request).list_favorite_products(int(account["id"])) if account is not None else [] ) return render( request, "workspace.html", page_title="Saved Products", body_class="workspace-page workspace-saved-products-page", workspace_view="saved-products", scope_route_id="workspace-saved-products", favorite_state=favorite_state, saved_products=saved_products, ) @app.get("/workspace/profile/", response_class=HTMLResponse) async def workspace_profile(request: Request) -> HTMLResponse: account = current_account(request) profile_stats = None if account is not None: database = get_db(request) profile_stats = { "member_since": FROZEN_CLOCK.split("T")[0], "favorite_count": database.count_favorites(int(account["id"])), "review_count": database.count_submissions(int(account["id"])), } return render( request, "workspace.html", page_title="My Profile", body_class="workspace-page workspace-profile-page", workspace_view="profile", scope_route_id="workspace-profile", favorite_state=None, profile_stats=profile_stats, ) @app.get("/software/search", response_class=HTMLResponse) async def software_search( request: Request, q: str = "", state: str = "results" ) -> HTMLResponse: normalized = state if state in {"results", "loading", "empty", "error"} else "results" results: list[dict] = [] similar_products: list[dict] = [] if normalized == "results": database = get_db(request) results = ( database.top_products(20) if not q.strip() else database.search_products(q, limit=25) ) if results: similar_products = database.alternatives_for( str(results[0]["id"]), limit=4 ) return render( request, "search.html", page_title="Software search", body_class="software-search-page", query=q, state=normalized, has_results=bool(results), results=results, similar_products=similar_products, scope_route_id=( "software-search" if normalized == "results" else "software-search-recovery-simulation" ), scope_state_ids=(normalized,), ) @app.get("/search/", response_class=HTMLResponse) async def public_search( request: Request, query: str = "", state: str = "results", ) -> HTMLResponse: """Preserve the current public search URL while sharing local results.""" if state == "results" and query.casefold() == "notion": return render_public_replay("software-search") return await software_search(request, q=query, state=state) @app.get("/categories/", response_class=HTMLResponse) async def categories_index(request: Request) -> HTMLResponse: return render_public_replay("categories-index") @app.get("/accounting-software/", response_class=HTMLResponse) async def accounting_software(request: Request) -> HTMLResponse: return render_public_replay("category-directory") @app.get("/accounting-software/s/free/", response_class=HTMLResponse) async def free_accounting_software(request: Request) -> HTMLResponse: return render_public_replay("subcategory-directory") CATEGORY_PAGE_SIZE = 25 CATEGORY_SORTS = ("recommended", "rating", "reviews") CATEGORY_FACETS = { "free": "Free", "mac": "Mac", "small-businesses": "Small Businesses", } def sorted_category_listing(products: list[dict], sort: str) -> list[dict]: if sort == "rating": return sorted(products, key=lambda p: (-(p["rating"] or 0), p["id"])) if sort == "reviews": return sorted( products, key=lambda p: (-(p["local_review_count"] or 0), p["id"]) ) return products def related_category_links(category_slug: str) -> list[dict[str, str]]: index = category_index() slugs = sorted(index) position = slugs.index(category_slug) related = [] for offset in (-2, -1, 1, 2, 3): neighbor = slugs[(position + offset) % len(slugs)] if neighbor != category_slug: related.append({"slug": neighbor, "label": index[neighbor]}) return related[:5] def render_category_listing( request: Request, *, category_slug: str, category_name: str, products: list[dict], listing_provenance: str, page: int, sort: str, facets: list[dict[str, str]] | None, search_term: str = "", ) -> HTMLResponse: if search_term: needle = search_term.casefold() products = [ product for product in products if needle in str(product["name"]).casefold() ] feature_counts: dict[str, int] = {} for product in products: for feature in product.get("features") or []: feature_counts[feature] = feature_counts.get(feature, 0) + 1 rail_features = [ feature for feature, _ in sorted( feature_counts.items(), key=lambda item: (-item[1], item[0]) )[:10] ] page_count = max( 1, (len(products) + CATEGORY_PAGE_SIZE - 1) // CATEGORY_PAGE_SIZE ) page = min(max(page, 1), page_count) start = (page - 1) * CATEGORY_PAGE_SIZE return render( request, "category_directory.html", page_title=f"Best {category_name} Software 2026 Reviews", body_class="category-directory-page", category_slug=category_slug, category_name=category_name, products=products[start : start + CATEGORY_PAGE_SIZE], total_count=len(products), listing_provenance=listing_provenance, page=page, page_count=page_count, sort=sort, facets=facets, search_term=search_term, rail_features=rail_features, related_categories=related_category_links(category_slug), ) # Registered after the literal /accounting-software/ routes above so those keep # serving their frozen captures; Starlette matches routes in registration order. @app.get("/{category_slug}-software/", response_class=HTMLResponse) async def category_directory( request: Request, category_slug: str, page: int = 1, sort: str = "recommended", search: str = "", ) -> Response: """Resolve one of the 1001 category routes named by the frozen directory. A slug the frozen directory never listed stays a 404 -- inventing categories would misrepresent the source. A listed slug renders its catalog-backed directory; listings whose membership was assembled locally rather than captured say so via the rendered provenance disclosure. """ label = category_label(category_slug) if label is None: return render_public_replay("not-found", status_code=404) db = get_db(request) products = sorted_category_listing( db.products_for_category(category_slug), sort if sort in CATEGORY_SORTS else "recommended", ) return render_category_listing( request, category_slug=category_slug, category_name=label, products=products, listing_provenance=db.category_listing_provenance(category_slug) or "derived", page=page, sort=sort if sort in CATEGORY_SORTS else "recommended", facets=[ {"slug": slug, "label": f"{name} {label}"} for slug, name in CATEGORY_FACETS.items() ], search_term=" ".join(search.split())[:80], ) @app.get("/p/186596/Notion/", response_class=HTMLResponse) async def notion_profile(request: Request) -> HTMLResponse: if current_account(request) is None: return render_public_replay("product-profile") return render( request, "profile.html", page_title="Notion software", body_class="notion-profile-page", profile_reviews=review_cards(1)[:10], scope_route_id="notion-profile", scope_state_ids=("profile", "review-summary"), ) @app.get("/p/186596/Notion/reviews/", response_class=HTMLResponse) async def notion_reviews( request: Request, page: int = 1, state: str = "review-summary", sort: str = "most-helpful", rating: str = "all", company_size: str = "all", role: str = "all", length_of_use: str = "all", frequency: str = "all", ) -> HTMLResponse: if current_account(request) is None and not request.url.query: return render_public_replay("product-reviews") current_page = min(max(page, 1), REVIEW_PAGE_COUNT) review_state = ( state if state in {"review-summary", "filter-display"} else "review-summary" ) filter_values = { "sort": ( sort if sort in {"most-helpful", "newest"} else "most-helpful" ), "rating": rating if rating in {"all", "5"} else "all", "company_size": ( company_size if company_size in {"all", "1-10"} else "all" ), "role": role if role in {"all", "manager"} else "all", "length_of_use": ( length_of_use if length_of_use in {"all", "1-2-years"} else "all" ), "frequency": ( frequency if frequency in {"all", "daily"} else "all" ), } # Page over the filtered set, not the whole corpus, so the counter and the # pager describe the reviews actually on screen. matching_reviews = select_reviews(filter_values) matching_total = len(matching_reviews) page_count = max( 1, (matching_total + REVIEW_PAGE_SIZE - 1) // REVIEW_PAGE_SIZE ) current_page = min(current_page, page_count) visible = matching_reviews[ (current_page - 1) * REVIEW_PAGE_SIZE : current_page * REVIEW_PAGE_SIZE ] first_review = (current_page - 1) * REVIEW_PAGE_SIZE + 1 if visible else 0 last_review = (current_page - 1) * REVIEW_PAGE_SIZE + len(visible) return render( request, "reviews.html", page_title="Notion reviews", body_class="notion-reviews-page", review_cards=visible, review_pages=range(1, page_count + 1), current_page=current_page, review_state=review_state, review_filters=filter_values, first_review=first_review, last_review=last_review, local_review_total=LOCAL_REVIEW_TOTAL, local_review_average=LOCAL_REVIEW_AVERAGE, matching_review_total=matching_total, filters_active=any( value != "all" for key, value in filter_values.items() if key != "sort" ), scope_route_id="notion-reviews", scope_state_ids=(review_state,), ) @app.get("/p/186596/Notion/alternatives/", response_class=HTMLResponse) async def notion_alternatives(request: Request) -> HTMLResponse: return render_public_replay("product-alternatives") @app.get("/p/186596/Notion/pricing/", response_class=HTMLResponse) async def notion_pricing(request: Request) -> HTMLResponse: return render_public_replay("product-pricing") def resolve_catalog_product( request: Request, product_id: str, product_slug: str, subpage: str = "" ) -> dict | Response: """The catalog product for a /p/ URL, or the 404/308 response instead.""" product = get_db(request).get_product(product_id) if product is None or not product.get("url_slug"): return render_public_replay("not-found", status_code=404) if product_slug != product["url_slug"]: return RedirectResponse( f"/p/{product_id}/{product['url_slug']}/{subpage}", status_code=308 ) return product def product_primary_category( request: Request, product: Mapping[str, object] ) -> dict[str, str] | None: for slug in get_db(request).categories_for_product(str(product["id"])): label = category_label(slug) if label: return {"slug": slug, "label": label} return None # Registered after the literal Notion routes above, which keep serving their # frozen captures; every other catalog product renders the template family. @app.get("/p/{product_id}/{product_slug}/", response_class=HTMLResponse) async def product_profile_page( request: Request, product_id: str, product_slug: str ) -> Response: product = resolve_catalog_product(request, product_id, product_slug) if isinstance(product, Response): return product corpus = product_review_corpus(product) category_chips = [ {"slug": slug, "label": category_label(slug)} for slug in get_db(request).categories_for_product(product_id)[:5] if category_label(slug) ] return render( request, "product_profile.html", page_title=f"{product['name']} Software Reviews, Pros and Cons", body_class="product-profile-page", product=product, sub_ratings=profile_sub_ratings(product), primary_category=(category_chips[0] if category_chips else None), category_chips=category_chips, top_reviews=corpus[:3], alternatives=get_db(request).alternatives_for(product_id, limit=8), ) @app.get("/p/{product_id}/{product_slug}/reviews/", response_class=HTMLResponse) async def product_reviews_page( request: Request, product_id: str, product_slug: str, page: int = 1, sort: str = "most-helpful", rating: str = "all", company_size: str = "all", role: str = "all", length_of_use: str = "all", frequency: str = "all", ) -> Response: product = resolve_catalog_product( request, product_id, product_slug, subpage="reviews/" ) if isinstance(product, Response): return product corpus = product_review_corpus(product) filter_values = { "sort": sort if sort in ("most-helpful", "newest") else "most-helpful", "rating": rating, "company_size": company_size, "role": role, "length_of_use": length_of_use, "frequency": frequency, } submitted = [ { "author": row["display_name"], "role": "Verified member", "industry": "Submitted on this edition", "tenure": "6-12 months", "company_size": "1-10", "frequency": "daily", "title": "Member review", "rating": int(row["rating"]), "rating_class": f"rating-{int(row['rating'])}", "date": "August 2, 2026", "date_sort": "2026-08-02", "overall": row["review_text"], "pros": "", "cons": "", "avatar": REVIEW_AVATARS[0], "local_number": 0, } for row in get_db(request).submissions_for_product(product_id) ] filtered = select_reviews(filter_values, corpus) rows = submitted + filtered if page == 1 and not request.url.query else filtered page_count = max(1, (len(rows) + REVIEW_PAGE_SIZE - 1) // REVIEW_PAGE_SIZE) current_page = min(max(page, 1), page_count) start = (current_page - 1) * REVIEW_PAGE_SIZE histogram = [ (star, sum(1 for card in corpus if card["rating"] == star)) for star in (5, 4, 3, 2, 1) ] return render( request, "product_reviews.html", page_title=f"{product['name']} Reviews 2026", body_class="product-reviews-page", product=product, overall_rating=round(float(product["rating"] or 4.2), 1), total_reviews=len(corpus), histogram=histogram, review_filters=filter_values, page_reviews=rows[start : start + REVIEW_PAGE_SIZE], page_count=page_count, current_page=current_page, alternatives=get_db(request).alternatives_for(product_id, limit=4), ) @app.get( "/p/{product_id}/{product_slug}/alternatives/", response_class=HTMLResponse ) async def product_alternatives_page( request: Request, product_id: str, product_slug: str ) -> Response: product = resolve_catalog_product( request, product_id, product_slug, subpage="alternatives/" ) if isinstance(product, Response): return product return render( request, "product_alternatives.html", page_title=f"Top {product['name']} Alternatives 2026", body_class="product-alternatives-page", product=product, primary_category=product_primary_category(request, product), alternatives=get_db(request).alternatives_for(product_id, limit=10), ) @app.get("/p/{product_id}/{product_slug}/pricing/", response_class=HTMLResponse) async def product_pricing_page( request: Request, product_id: str, product_slug: str ) -> Response: product = resolve_catalog_product( request, product_id, product_slug, subpage="pricing/" ) if isinstance(product, Response): return product starting = product.get("pricing") or "Contact vendor" pricing_tiers = [ { "name": "Starter", "price": starting, "cadence": "per user", "points": [ "Core features for small teams", "Standard support and updates", "Cancel any time", ], "highlight": False, }, { "name": "Business", "price": "Contact vendor", "cadence": "", "points": [ "Everything in Starter", "Advanced controls and reporting", "Priority support", ], "highlight": True, }, { "name": "Enterprise", "price": "Contact vendor", "cadence": "", "points": [ "Custom deployment options", "Security and compliance reviews", "Dedicated onboarding", ], "highlight": False, }, ] return render( request, "product_pricing.html", page_title=f"{product['name']} Pricing 2026", body_class="product-pricing-page", product=product, pricing_tiers=pricing_tiers, ) @app.get("/compare/", response_class=HTMLResponse) async def public_compare_builder(request: Request) -> HTMLResponse: return render_public_replay("compare-empty") @app.get("/compare/selected", response_class=HTMLResponse) async def selected_product_comparison(request: Request, products: str = "") -> Response: """Render the two-to-four products chosen in the public comparison builder.""" product_ids = list( dict.fromkeys( part.strip() for part in products.split(",") if part.strip() ) ) if not 2 <= len(product_ids) <= 4 or any( not part.isdigit() for part in product_ids ): return JSONResponse( {"detail": "Choose between two and four products to compare."}, status_code=400, ) database = get_db(request) selected_products = [ database.get_product(product_id) for product_id in product_ids ] if any(product is None for product in selected_products): return JSONResponse( {"detail": "One or more products were not found."}, status_code=404, ) return render( request, "compare_selected.html", page_title="Compare selected software", body_class="comparison-selected-page", products=selected_products, ) @app.get( "/compare/153472-253516/Startquestion-vs-SurveyMonkey", response_class=HTMLResponse, ) @app.get( "/compare/186596-147657/Notion-vs-monday-com", response_class=HTMLResponse, ) async def public_product_comparison(request: Request) -> HTMLResponse: return render_public_replay("compare-products") # Registered after the two frozen pair literals above; any other catalog pair # renders the data-driven comparison template. @app.get("/compare/{pair_ids}/{pair_names}", response_class=HTMLResponse) async def catalog_product_comparison( request: Request, pair_ids: str, pair_names: str ) -> Response: parts = pair_ids.split("-") if len(parts) != 2 or parts[0] == parts[1]: return render_public_replay("not-found", status_code=404) database = get_db(request) product_a = database.get_product(parts[0]) product_b = database.get_product(parts[1]) if ( product_a is None or product_b is None or not product_a.get("url_slug") or not product_b.get("url_slug") ): return render_public_replay("not-found", status_code=404) canonical_ids = "-".join(sorted(parts)) if pair_ids != canonical_ids: product_a, product_b = ( (product_a, product_b) if canonical_ids.startswith(str(product_a["id"])) else (product_b, product_a) ) first, second = sorted((product_a, product_b), key=lambda p: str(p["id"])) canonical_names = f"{first['url_slug']}-vs-{second['url_slug']}" if pair_ids != canonical_ids or pair_names != canonical_names: return RedirectResponse( f"/compare/{canonical_ids}/{canonical_names}", status_code=308 ) swap_options = [ option for option in database.alternatives_for(str(first["id"]), limit=6) if str(option["id"]) != str(second["id"]) ][:4] return render( request, "compare_pair.html", page_title=f"{first['name']} vs {second['name']} 2026 Comparison", body_class="comparison-pair-page", product_a=first, product_b=second, swap_options=swap_options, ) @app.get( "/project-management-software/shortlist/", response_class=HTMLResponse, ) async def project_management_shortlist(request: Request) -> HTMLResponse: return render_public_replay("shortlist") # Registered after the literal frozen shortlist route above so that capture # keeps serving byte-identical; every other category gets its catalog listing. @app.get("/{category_slug}-software/shortlist/", response_class=HTMLResponse) async def category_shortlist(request: Request, category_slug: str) -> Response: label = category_label(category_slug) if label is None: return render_public_replay("not-found", status_code=404) db = get_db(request) products = sorted_category_listing( db.products_for_category(category_slug), "rating" )[:10] return render( request, "category_shortlist.html", page_title=f"2026 Capterra Shortlist for {label}", body_class="category-shortlist-page", category_slug=category_slug, category_name=label, products=products, listing_provenance=db.category_listing_provenance(category_slug) or "derived", ) @app.get("/{category_slug}-software/s/{facet}/", response_class=HTMLResponse) async def category_facet( request: Request, category_slug: str, facet: str, page: int = 1, sort: str = "recommended", ) -> Response: label = category_label(category_slug) facet_name = CATEGORY_FACETS.get(facet) if label is None or facet_name is None: return render_public_replay("not-found", status_code=404) db = get_db(request) listing = db.products_for_category(category_slug) subset = [ product for product in listing if int( hashlib.sha256( f"capterra-facet:{facet}:{product['id']}".encode("utf-8") ).hexdigest()[:8], 16, ) % 5 < 3 ] or listing[: max(1, len(listing) // 2)] return render_category_listing( request, category_slug=category_slug, category_name=f"{facet_name} {label}", products=sorted_category_listing( subset, sort if sort in CATEGORY_SORTS else "recommended" ), listing_provenance="derived", page=page, sort=sort if sort in CATEGORY_SORTS else "recommended", facets=None, ) @app.get("/reviews/search/", response_class=HTMLResponse) async def review_search(request: Request) -> HTMLResponse: if current_account(request) is None: return render_public_replay("review-search") return render( request, "review_search.html", page_title="Write a software review", body_class="review-search-page", scope_route_id="review-search", scope_state_ids=( "product-search", "industry-selection", "disabled-next", ), ) @app.get("/our-story/", response_class=HTMLResponse) async def our_story(request: Request) -> HTMLResponse: return render_public_replay("our-story") @app.get("/careers", response_class=HTMLResponse, include_in_schema=False) async def careers(request: Request) -> HTMLResponse: """Describe the local careers boundary without inventing live vacancies.""" return render( request, "careers.html", page_title="Careers at Capterra demo", body_class="careers-page", ) @app.get("/resources/", response_class=HTMLResponse) async def resources_index(request: Request) -> HTMLResponse: return render_public_replay("resources-index") @app.post("/api/ebook/request") async def request_ebook(request: Request) -> JSONResponse: """Acknowledge the public guide request without external mail side effects.""" values = await urlencoded_form(request) email = ( unicodedata.normalize("NFC", values.get("emailAddress", "")) .strip() .casefold() ) if ( len(email) > 254 or re.fullmatch(r"[^\s@]+@[^\s@]+\.[^\s@]+", email) is None ): return JSONResponse( {"detail": "Please enter a valid email address."}, status_code=400, ) digest = hashlib.sha256(email.encode("utf-8")).hexdigest() digests: set[str] = request.app.state.ebook_request_digests duplicate = digest in digests if not duplicate: if len(digests) >= 1000: digests.clear() digests.add(digest) return JSONResponse( { "ok": True, "duplicate": duplicate, "message": ( "Request already received. No email was sent by this WebsiteBench demo." if duplicate else "Request received. No email was sent by this WebsiteBench demo." ), } ) @app.get("/glossary/", include_in_schema=False) async def glossary_alias() -> RedirectResponse: return RedirectResponse("/resources/", status_code=308) @app.get("/resources/how-we-verify-reviews/", response_class=HTMLResponse) async def review_verification_policy(request: Request) -> HTMLResponse: return render_public_replay("resource-article") @app.get("/resources/news/", response_class=HTMLResponse) async def resources_news(request: Request) -> HTMLResponse: return render_public_replay("resources-news") @app.get("/legal/terms-of-use/", response_class=HTMLResponse) async def terms_of_use(request: Request) -> HTMLResponse: return render_public_replay("legal-terms") LEGAL_POLICY_SECTIONS: dict[str, tuple[str, list[dict[str, str]]]] = { "privacy": ( "Privacy Policy", [ {"title": "Scope", "body": "This policy explains how the Capterra WebsiteBench demo handles information while you browse local pages and use local account features."}, {"title": "Personal Information We Collect", "body": "The demo collects only the information required for the local feature you choose. It does not import production Capterra accounts or vendor data."}, {"title": "How We Use Personal Information", "body": "Information is used to provide local sessions, reviews, saved products, and other explicitly requested demo features."}, {"title": "Reviews and User-Generated Content", "body": "Submitted local reviews are displayed within this isolated site and remain separate from production Capterra services."}, {"title": "How We Disclose Personal Information", "body": "The demo does not sell personal information or send it to advertising partners."}, {"title": "Legal Bases for Processing", "body": "Processing is limited to providing requested local functionality and protecting the integrity of the demo."}, {"title": "Cookies and Similar Technologies", "body": "Essential local cookies maintain sessions and security boundaries. Third-party advertising scripts are not required."}, {"title": "Marketing Choices", "body": "This demo does not enroll visitors in production marketing programs."}, {"title": "Data Retention", "body": "Local demo data follows the deployment retention and isolation settings."}, {"title": "International Data Transfers", "body": "No production cross-border transfer is created by browsing this local replica."}, ], ), "vendor": ( "General Vendor Terms", [ {"title": "Scope", "body": "These terms describe the boundary between this buyer-facing demo and external G2 Digital Markets vendor services."}, {"title": "Vendor Accounts", "body": "Vendor accounts, product claims, lead programs, and commercial listings are provided only by the external vendor portal."}, {"title": "Product Information", "body": "Product information shown here is a local benchmark catalog and does not update a production listing."}, {"title": "Reviews", "body": "Local review fixtures do not create, modify, or moderate reviews on production Capterra."}, {"title": "Commercial Programs", "body": "No advertising purchase, lead order, or paid placement can be created in this deployment."}, ], ), "user": ( "General User Terms", [ {"title": "Using the Site", "body": "Use this replica to browse software, compare products, and exercise the local review workflow."}, {"title": "Accounts", "body": "Accounts created here are isolated local accounts and are not production Capterra credentials."}, {"title": "Acceptable Use", "body": "Do not attempt to submit unlawful content, interfere with the service, or misrepresent local benchmark data as production data."}, {"title": "User Content", "body": "You remain responsible for local content you choose to submit."}, {"title": "Availability", "body": "The benchmark deployment may change or reset as part of testing and evaluation."}, ], ), "transfer": ( "Data Transfer Addendum", [ {"title": "Purpose", "body": "This addendum documents that the local WebsiteBench deployment does not connect to production Capterra customer or vendor databases."}, {"title": "Data Isolation", "body": "Each site has distinct storage and session identity. Data is not shared with other WebsiteBench sites."}, {"title": "Security", "body": "Access controls, scoped cookies, and local runtime validation protect demo data."}, {"title": "Subprocessors", "body": "Only services declared by the active deployment runtime may process local demo data."}, {"title": "Deletion", "body": "Local data can be removed according to the benchmark environment lifecycle."}, ], ), } def render_legal_policy(request: Request, policy_id: str) -> HTMLResponse: title, sections = LEGAL_POLICY_SECTIONS[policy_id] return render( request, "legal_policy.html", page_title=title, body_class="legal-policy-page", policy_id=policy_id, policy_title=title, policy_sections=sections, ) @app.get("/legal/privacy-policy/", response_class=HTMLResponse) async def privacy_policy(request: Request) -> HTMLResponse: return render_legal_policy(request, "privacy") @app.get("/legal/general-vendor-terms/", response_class=HTMLResponse) async def general_vendor_terms(request: Request) -> HTMLResponse: return render_legal_policy(request, "vendor") @app.get("/legal/general-user-terms/", response_class=HTMLResponse) async def general_user_terms(request: Request) -> HTMLResponse: return render_legal_policy(request, "user") @app.get("/legal/data-transfer-addendum/", response_class=HTMLResponse) async def data_transfer_addendum(request: Request) -> HTMLResponse: return render_legal_policy(request, "transfer") @app.get( "/resources/category/accounting-and-finance/", response_class=HTMLResponse, ) async def accounting_resources(request: Request) -> HTMLResponse: return render_public_replay("resource-category") @app.get("/resources/author/david-jani/", response_class=HTMLResponse) async def resource_author(request: Request) -> HTMLResponse: return render_public_replay("resource-author") @app.get("/resources/accounting-automation/", response_class=HTMLResponse) async def accounting_automation(request: Request) -> HTMLResponse: return render_public_replay("resource-editorial-article") @app.get( "/resources/proprietary-data-research/", response_class=HTMLResponse, ) async def proprietary_data_research(request: Request) -> HTMLResponse: return render_public_replay("resource-research-index") @app.get("/resources/research-agenda/", response_class=HTMLResponse) async def research_agenda(request: Request) -> HTMLResponse: return render_public_replay("resource-research-agenda") @app.get("/_websitebench-missing-page/", response_class=HTMLResponse) @app.get("/faq", response_class=HTMLResponse) @app.get("/faq/", response_class=HTMLResponse) @app.get("/services", response_class=HTMLResponse) @app.get("/services/", response_class=HTMLResponse) @app.get("/faq/faqs-verification/", response_class=HTMLResponse) async def public_not_found(request: Request) -> HTMLResponse: replay_id = { "/faq": "faq", "/faq/": "faq", "/services": "services", "/services/": "services", "/faq/faqs-verification/": "faq-verification", }.get(request.url.path, "not-found") return render_public_replay(replay_id, status_code=404) @app.get("/vendors/", response_class=HTMLResponse) async def vendor_boundary( request: Request, capability: str = "commercial", ) -> HTMLResponse: if capability == "commercial" and "capability" not in request.query_params: response = render( request, "vendors_current.html", page_title="Capterra for Vendors", body_class="vendors-current-page", ) response.headers["X-WebsiteBench-Replay"] = "vendors" return response normalized_capability = ( capability if capability in {"commercial", "listing", "login"} else "commercial" ) boundary_state = ( "offline-boundary" if normalized_capability == "commercial" else "unavailable-capability" ) return render( request, "vendor_boundary.html", page_title="For software vendors", vendor_capability=normalized_capability, scope_route_id="vendor-boundary", scope_state_ids=(boundary_state, "return"), ) # --------------------------------------------------------------------------- # Honest destinations for controls whose real target is off this site # # Source evidence: materials/capterra/artifacts/parity/auth/signin/desktop/. # The header's "Join or Log in" opens an overlay offering CONTINUE WITH GOOGLE # and CONTINUE WITH LINKEDIN above a "Continue with email" fallback. Neither # provider can be honoured locally, and a provider button that silently does # nothing — or that quietly signs someone in — is the failure this boundary # exists to prevent. Each one is a real link to a page that names the # destination and says plainly it is not part of this edition; none of them # touches the session. # --------------------------------------------------------------------------- EXTERNAL_DESTINATIONS: dict[str, dict[str, str]] = { "google-auth": { "label": "Continue with Google", "description": ( "Signing in with a Google account is handled by Google and is not " "reproduced in this edition." ), "return_path": "/auth/login", "return_label": "Back to sign in", }, "linkedin-auth": { "label": "Continue with LinkedIn", "description": ( "Signing in with a LinkedIn account is handled by LinkedIn and is " "not reproduced in this edition." ), "return_path": "/auth/login", "return_label": "Back to sign in", }, "privacy-policy": { "label": "Privacy Policy", "description": ( "The Privacy Policy is published outside this edition and is not " "reproduced here. The Terms of Use are available locally." ), "return_path": "/legal/terms-of-use/", "return_label": "Read the Terms of Use", }, } EXTERNAL_REDIRECTS: dict[str, str] = { "careers": "https://company.g2.com/careers", "g2-get-listed": "https://app.g2digitalmarkets.com/get-listed/start", "g2-vendor-login": "https://app.g2digitalmarkets.com/", "g2-marketing": "https://www.g2digitalmarkets.com/", "linkedin": "https://www.linkedin.com/company/capterra", "x": "https://x.com/capterra", "facebook": "https://www.facebook.com/Capterra/", "instagram": "https://www.instagram.com/capterra/", "youtube": "https://www.youtube.com/user/CapterraTV", } @app.get("/out/external/{destination}") async def external_redirect(destination: str) -> RedirectResponse: """Redirect audited public links to their verified external destinations.""" target = EXTERNAL_REDIRECTS.get(destination) if target is None: return RedirectResponse(url="/", status_code=303) return RedirectResponse(url=target, status_code=307) @app.get("/out/vendor-site/{product_id}", response_class=HTMLResponse) async def vendor_site_boundary( request: Request, product_id: str ) -> HTMLResponse: """Every product 'Visit Website' CTA lands on this same-origin boundary.""" product = get_db(request).get_product(product_id) if product is None or not product.get("url_slug"): return render_public_replay("not-found", status_code=404) return render( request, "vendor_site_boundary.html", page_title=f"Visit {product['name']}", body_class="vendor-site-boundary-page", product=product, ) @app.get("/out/{destination}", response_class=HTMLResponse) async def external_boundary(request: Request, destination: str) -> HTMLResponse: value = EXTERNAL_DESTINATIONS.get(destination) if value is None: return render( request, "boundary.html", page_title="Page not found", destination=None, status_code=404, ) return render( request, "boundary.html", page_title=str(value["label"]), destination=value, ) @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=get_auth(request), session_token=request.cookies.get(AUTH_SESSION_COOKIE, ""), ) @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=get_auth(request), session_token=request.cookies.get(AUTH_SESSION_COOKIE, ""), ) # --------------------------------------------------------------------------- # One canonical account route family # # This site grew two names for the same handlers: `/auth/*` and # `/local/account/*`. `/auth/*` is canonical — every template links to it and # every redirect these handlers emit already targets it (`/auth/logout?state= # revoked`, `/auth/register/verify?...`). `/local/account/*` was a second set # of decorators on the same functions, so two URLs served one page with no # relationship between them. # # Navigating to an alias now lands on the canonical URL with a 308, query string # intact. The POST endpoints stay mounted at both names deliberately: the suite # asserts the PRG contract directly against the alias # (`test_fullstack_backend.py` posts to `/local/account/password/{forgot,verify, # reset}` with `follow_redirects=False` and requires 303), and answering 308 # there would replace the 303 those tests check with a redirect *to* the thing # they check — narrowing live coverage rather than adding to it. Every one of # them already ends on a canonical `/auth/*` location, so no alias URL survives # a completed flow. # --------------------------------------------------------------------------- CANONICAL_ACCOUNT_ROUTES: dict[str, str] = { "/local/account/register": "/auth/register", "/local/account/register/verify": "/auth/register/verify", "/local/account/sign-in": "/auth/login", "/local/account/sign-out": "/auth/logout", "/local/account/password/forgot": "/auth/password/forgot", "/local/account/password/verify": "/auth/password/verify", "/local/account/password/reset": "/auth/password/reset", "/local/account/inbox": "/auth/local-inbox", } @app.get("/local/account/{alias_path:path}", include_in_schema=False) async def canonical_account_redirect( request: Request, alias_path: str ) -> Response: target = CANONICAL_ACCOUNT_ROUTES.get( "/local/account/" + alias_path.rstrip("/") ) if target is None: return render_public_replay("not-found", status_code=404) query = request.url.query return RedirectResponse(f"{target}?{query}" if query else target, 308) @app.get("/auth/register", response_class=HTMLResponse) async def local_account_register( request: Request, state: str = "entry", next: str | None = None, restart: bool = False, ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-register", requested_state="entry" if restart else state, canonicalize_state=not restart, next_path=safe_registration_next(next), restart_flow=restart, ) @app.post("/auth/register", response_class=HTMLResponse) @app.post("/local/account/register", response_class=HTMLResponse) async def local_account_register_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, created = ensure_auth_session(request) next_path = safe_registration_next(values.get("next")) if not valid_auth_csrf(values, token): response = render_r2_contract_state( request, route_id="auth-register", requested_state="invalid", status_code=403, form_error="Your request expired. Reload the page and try again.", ) if created: set_auth_cookie(response, token) return response if PUBLIC_REGISTRATION_VERIFICATION is not None: auth_store = get_auth(request) database = get_db(request) try: auth_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=auth_store, session_token=token, email=values.get("email", ""), ) if not ticket: return render_r2_contract_state( request, route_id="auth-register", requested_state="invalid", status_code=422, form_error="Verify this email address before creating the account.", ) completed = auth_store.complete_externally_verified_registration( token, email=values.get("email", ""), display_name=values.get("display_name", ""), password=values.get("password", ""), subject_factory=lambda connection, account: ( database.create_account_subject( connection, account_id=str(account["account_id"]), display_name=str(account["display_name"]), email=str(account["email"]), ) ), session_rotation_callback=( database.transfer_anonymous_comparison_in_transaction ), ) except VerificationUnavailable: return render_r2_contract_state( request, route_id="auth-register", requested_state="invalid", status_code=503, form_error="Email verification is temporarily unavailable.", ) except AuthError as error: return render_r2_contract_state( request, route_id="auth-register", requested_state="invalid", status_code=422, form_error=str(error), ) new_token = str(completed["session_token"]) database.record_auth_transition( auth_store.session_owner_digest(new_token), "registration-verified", ) response = RedirectResponse(next_path, status_code=303) set_auth_cookie(response, new_token) return response try: get_auth(request).start_registration( token, email=values.get("email", ""), display_name=values.get("display_name", ""), password=values.get("password", ""), restart_invalid_flow=values.get("restart") == "1", ) except AuthRateLimited as error: return render_r2_contract_state( request, route_id="auth-register", requested_state="rate-limited", status_code=429, form_error=str(error), ) except AuthConflict as error: return render_r2_contract_state( request, route_id="auth-register", requested_state="duplicate", status_code=409, form_error=str(error), ) except AuthError as error: return render_r2_contract_state( request, route_id="auth-register", requested_state="invalid", status_code=422, form_error=str(error), ) response = RedirectResponse( "/auth/register/verify?" + urlencode({"next": next_path}), status_code=303, ) if created: set_auth_cookie(response, token) return response @app.get("/auth/register/verify", response_class=HTMLResponse) async def local_account_register_verify( request: Request, state: str = "challenge", next: str | None = None ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-register-verify", requested_state=state, next_path=safe_registration_next(next), ) @app.post("/auth/register/verify", response_class=HTMLResponse) @app.post("/local/account/register/verify", response_class=HTMLResponse) async def local_account_register_verify_submit( request: Request, ) -> HTMLResponse: values = await urlencoded_form(request) token, _, _ = ensure_auth_session(request) if not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="auth-register-verify", requested_state="challenge", status_code=403, form_error="Your request expired. Reload the page and try again.", ) try: auth_store = get_auth(request) auth_store.verify_registration_code(token, values.get("code", "")) database = get_db(request) completed = auth_store.complete_registration( token, subject_factory=lambda connection, account: ( database.create_account_subject( connection, account_id=str(account["account_id"]), display_name=str(account["display_name"]), email=str(account["email"]), ) ), session_rotation_callback=( database.transfer_anonymous_comparison_in_transaction ), ) except AuthError as error: if isinstance(error, AuthLocked): state = "locked" elif isinstance(error, (AuthValidationError, AuthRejected)): state = "invalid" else: state = "stale" return render_r2_contract_state( request, route_id="auth-register-verify", requested_state=state, status_code=422, form_error=str(error), ) response = RedirectResponse( "/auth/register/verify?" + urlencode({"next": safe_registration_next(values.get("next"))}), status_code=303, ) new_token = str(completed["session_token"]) get_db(request).record_auth_transition( get_auth(request).session_owner_digest(new_token), "registration-verified", ) set_auth_cookie(response, new_token) return response @app.get("/auth/login", response_class=HTMLResponse) async def local_account_sign_in( request: Request, state: str = "entry", next: str | None = None ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-login", requested_state=state, next_path=safe_next(next), ) @app.post("/auth/login", response_class=HTMLResponse) @app.post("/local/account/sign-in", response_class=HTMLResponse) async def local_account_sign_in_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, _ = ensure_auth_session(request) if not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="auth-login", requested_state="invalid", status_code=403, form_error="Your request expired. Reload the page and try again.", ) try: signed_in = get_auth(request).sign_in( token, email=values.get("email", ""), password=values.get("password", ""), session_rotation_callback=( get_db(request).transfer_anonymous_comparison_in_transaction ), ) except AuthError: return render_r2_contract_state( request, route_id="auth-login", requested_state="invalid", status_code=401, form_error="The email or password is incorrect.", ) response = RedirectResponse(safe_next(values.get("next")), status_code=303) set_auth_cookie(response, str(signed_in["session_token"])) return response @app.get("/auth/logout", response_class=HTMLResponse) async def local_account_sign_out( request: Request, state: str = "active" ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-logout", requested_state=state ) @app.post("/auth/logout", response_class=HTMLResponse) @app.post("/local/account/sign-out", response_class=HTMLResponse) async def local_account_sign_out_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token = request.cookies.get(AUTH_SESSION_COOKIE, "") if not token or not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="auth-logout", requested_state="active", status_code=403, form_error="Your request expired. Reload the page and try again.", ) get_auth(request).sign_out(token) get_db(request).delete_session_for_cookie( request.cookies.get(SESSION_COOKIE) ) response = RedirectResponse("/auth/logout?state=revoked", 303) response.delete_cookie(AUTH_SESSION_COOKIE, path="/") response.delete_cookie(SESSION_COOKIE, path="/") return response @app.get("/auth/password/forgot", response_class=HTMLResponse) async def local_password_forgot( request: Request, state: str = "entry", restart: bool = False ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-password-forgot", requested_state="entry" if restart else state, canonicalize_state=not restart, restart_flow=restart, ) @app.post("/auth/password/forgot", response_class=HTMLResponse) @app.post("/local/account/password/forgot", response_class=HTMLResponse) async def local_password_forgot_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, created = ensure_auth_session(request) if not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="auth-password-forgot", requested_state="entry", status_code=403, form_error="Your request expired. Reload the page and try again.", ) try: get_auth(request).start_password_reset( token, email=values.get("email", ""), restart_invalid_flow=values.get("restart") == "1", ) except AuthRateLimited as error: return render_r2_contract_state( request, route_id="auth-password-forgot", requested_state="rate-limited", status_code=429, form_error=str(error), ) except AuthValidationError as error: return render_r2_contract_state( request, route_id="auth-password-forgot", requested_state="entry", status_code=422, form_error=str(error), ) response = RedirectResponse( "/auth/password/forgot?state=generic-response", 303 ) if created: set_auth_cookie(response, token) return response @app.get("/auth/password/verify", response_class=HTMLResponse) async def local_password_verify( request: Request, state: str = "challenge" ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-password-verify", requested_state=state ) @app.post("/auth/password/verify", response_class=HTMLResponse) @app.post("/local/account/password/verify", response_class=HTMLResponse) async def local_password_verify_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, _ = ensure_auth_session(request) if not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="auth-password-verify", requested_state="challenge", status_code=403, form_error="Your request expired. Reload the page and try again.", ) try: get_auth(request).verify_password_reset_code( token, values.get("code", "") ) except AuthError as error: if isinstance(error, AuthLocked): state = "locked" elif isinstance(error, (AuthValidationError, AuthRejected)): state = "invalid" else: state = "stale" return render_r2_contract_state( request, route_id="auth-password-verify", requested_state=state, status_code=422, form_error=str(error), ) return RedirectResponse("/auth/password/reset?state=verified", 303) @app.get("/auth/password/reset", response_class=HTMLResponse) async def local_password_reset( request: Request, state: str = "verified" ) -> HTMLResponse: return render_r2_contract_state( request, route_id="auth-password-reset", requested_state=state ) @app.post("/auth/password/reset", response_class=HTMLResponse) @app.post("/local/account/password/reset", response_class=HTMLResponse) async def local_password_reset_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, _ = ensure_auth_session(request) if not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="auth-password-reset", requested_state="verified", status_code=403, form_error="Your request expired. Reload the page and try again.", ) try: new_token = get_auth(request).complete_password_reset( token, new_password=values.get("password", ""), session_rotation_callback=( get_db(request).transfer_anonymous_comparison_in_transaction ), ) except AuthError as error: state = ( "invalid" if isinstance(error, (AuthValidationError, AuthRejected)) else "verified" ) return render_r2_contract_state( request, route_id="auth-password-reset", requested_state=state, status_code=422, form_error=str(error), ) response = RedirectResponse( "/auth/password/reset?state=complete", 303 ) get_db(request).record_auth_transition( get_auth(request).session_owner_digest(new_token), "password-reset-complete", ) set_auth_cookie(response, new_token) return response @app.get("/auth/local-inbox", response_class=HTMLResponse) async def local_account_inbox( request: Request, state: str | None = None, next: str | None = None ) -> HTMLResponse: token, _, _ = ensure_auth_session(request) purpose = request.query_params.get("purpose", "registration") if purpose not in {"registration", "password-reset"}: purpose = "registration" mail = get_auth(request).local_mail_for_session(token, purpose=purpose) return render_r2_contract_state( request, route_id="auth-local-inbox", requested_state=state or ("local-only" if mail else "empty"), local_mail=mail, mail_purpose=purpose, next_path=safe_registration_next(next), ) @app.post("/auth/local-inbox/retry", response_class=HTMLResponse) @app.post("/local/account/inbox/retry", response_class=HTMLResponse) async def local_account_inbox_retry(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, created = ensure_auth_session(request) purpose = values.get("purpose", "registration") if purpose not in {"registration", "password-reset"}: purpose = "registration" if not valid_auth_csrf(values, token): response = render_r2_contract_state( request, route_id="auth-local-inbox", requested_state="smtp-failed", status_code=403, mail_purpose=purpose, form_error="Your request expired. Reload the page and try again.", ) if created: set_auth_cookie(response, token) return response queued = get_auth(request).retry_failed_mail_for_session( token, purpose=purpose ) if not queued: response = render_r2_contract_state( request, route_id="auth-local-inbox", requested_state="smtp-failed", status_code=409, mail_purpose=purpose, form_error="This message cannot be retried.", ) if created: set_auth_cookie(response, token) return response response = RedirectResponse( "/auth/local-inbox?" + urlencode({"purpose": purpose}), status_code=303, ) if created: set_auth_cookie(response, token) return response @app.get("/compare", response_class=HTMLResponse) @app.get("/local/software/comparison", response_class=HTMLResponse) async def local_software_comparison( request: Request, state: str | None = None, restart: bool = False ) -> HTMLResponse: existing_token = request.cookies.get(AUTH_SESSION_COOKIE) actual = ( get_db(request).anonymous_comparison_state( comparison_owner_id(request, existing_token) ) if existing_token and get_auth(request).resolve_session(existing_token) is not None else {"product_ids": [], "version": 0} ) return render_r2_contract_state( request, route_id="local-comparison", requested_state=( "selection-empty" if restart else state or ( "comparison-ready" if actual["product_ids"] else "cleared-aftercare" if int(actual["version"]) > 0 else "selection-empty" ) ), canonicalize_state=not restart, comparison_state=( {"product_ids": [], "version": actual["version"]} if restart else actual ), ) @app.post("/compare", response_class=HTMLResponse) @app.post("/local/software/comparison", response_class=HTMLResponse) async def local_software_comparison_submit(request: Request) -> HTMLResponse: values = await urlencoded_form(request) token, _, created = ensure_auth_session(request) if not token or not valid_auth_csrf(values, token): response = render_r2_contract_state( request, route_id="local-comparison", requested_state="retry-selection", status_code=403, form_error="Your request expired. Reload the page and try again.", ) if created: set_auth_cookie(response, token) return response selected = [ product_id for key, product_id in ( ("product_notion", PRODUCT_ID), ("product_asana", "asana-101"), ("product_monday", "monday-102"), ) if values.get(key) == "on" ] owner_session_id = comparison_owner_id(request, token) def retry_comparison_state() -> dict[str, object]: current = get_db(request).anonymous_comparison_state(owner_session_id) return { "product_ids": selected, "version": int(current["version"]), } try: result = get_db(request).update_anonymous_comparison( owner_session_id=owner_session_id, product_ids=selected, expected_version=int(values.get("expected_version", "-1")), idempotency_key=values.get("idempotency_key", ""), ) except (ValueError, backend_db.IdempotencyConflict) as error: return render_r2_contract_state( request, route_id="local-comparison", requested_state="invalid-selection", status_code=422, form_error=str(error), comparison_state=retry_comparison_state(), ) except backend_db.StaleVersionError as error: return render_r2_contract_state( request, route_id="local-comparison", requested_state="retry-selection", status_code=409, form_error=str(error), comparison_state=retry_comparison_state(), ) response = RedirectResponse( "/compare?state=" + ( "comparison-ready" if result["product_ids"] else "cleared-aftercare" ), 303, ) if created: set_auth_cookie(response, token) return response def render_catalog_favorite_page( request: Request, product_id: str, next_value: str | None, *, status_code: int = 200, form_error: str = "", ) -> HTMLResponse: """The save/unsave page for any catalog product other than Notion.""" product = get_db(request).get_product(product_id) if product is None or not product.get("url_slug"): return render_public_replay("not-found", status_code=404) account = current_account(request) favorite_state = ( get_db(request).favorite_state(int(account["id"]), product_id) if account is not None else {"product_id": product_id, "present": False, "version": 0} ) next_path = "" if next_value: resolved = safe_next(next_value) next_path = resolved if resolved == next_value else "" return render( request, "product_favorite.html", status_code=status_code, page_title=f"Save {product['name']}", body_class="product-favorite-page", product=product, favorite_state=favorite_state, favorite_display_state=( "present" if favorite_state["present"] else "absent" ), next_path=next_path, form_error=form_error, ) async def submit_catalog_favorite( request: Request, product_id: str ) -> HTMLResponse: product = get_db(request).get_product(product_id) if product is None or not product.get("url_slug"): return render_public_replay("not-found", status_code=404) account = current_account(request) if account is None: return RedirectResponse( f"/auth/login?next=/favorites/software/{product_id}", status_code=303, ) values = await urlencoded_form(request) next_value = values.get("next") or None token = request.cookies.get(AUTH_SESSION_COOKIE, "") if not token or not valid_auth_csrf(values, token): return render_catalog_favorite_page( request, product_id, next_value, status_code=403, form_error="Your request expired. Reload the page and try again.", ) try: get_db(request).update_favorite( account_id=int(account["id"]), product_id=product_id, present=values.get("action") == "add", expected_version=int(values.get("expected_version", "-1")), idempotency_key=values.get("idempotency_key", ""), ) except ( ValueError, backend_db.IdempotencyConflict, backend_db.StaleVersionError, ) as error: return render_catalog_favorite_page( request, product_id, next_value, status_code=409, form_error=str(error), ) return RedirectResponse( f"/favorites/software/{product_id}" + (f"?next={quote(next_value)}" if next_value else ""), status_code=303, ) @app.get("/favorites/software/{product_id}", response_class=HTMLResponse) @app.get("/local/software/favorites", response_class=HTMLResponse) async def local_software_favorites( request: Request, state: str | None = None, product_id: str = PRODUCT_ID, next: str | None = None, ) -> HTMLResponse: if product_id != PRODUCT_ID: return render_catalog_favorite_page(request, product_id, next) account = current_account(request) actual = ( get_db(request).favorite_state(int(account["id"])) if account is not None else {"product_id": PRODUCT_ID, "present": False, "version": 0} ) return render_r2_contract_state( request, route_id="software-favorites", requested_state=state or ( "present" if actual["present"] else "removed" if int(actual["version"]) > 0 else "absent" ), favorite_state=actual, ) @app.post("/favorites/software/{product_id}", response_class=HTMLResponse) @app.post("/local/software/favorites", response_class=HTMLResponse) async def local_software_favorites_submit( request: Request, product_id: str = PRODUCT_ID ) -> HTMLResponse: if product_id != PRODUCT_ID: return await submit_catalog_favorite(request, product_id) account = current_account(request) if account is None: return RedirectResponse( f"/auth/login?next=/favorites/software/{PRODUCT_ID}", status_code=303, ) values = await urlencoded_form(request) token = request.cookies.get(AUTH_SESSION_COOKIE, "") if not token or not valid_auth_csrf(values, token): return render_r2_contract_state( request, route_id="software-favorites", requested_state="absent", status_code=403, form_error="Your request expired. Reload the page and try again.", ) desired = values.get("action") == "add" try: result = get_db(request).update_favorite( account_id=int(account["id"]), product_id=values.get("product_id", PRODUCT_ID), present=desired, expected_version=int(values.get("expected_version", "-1")), idempotency_key=values.get("idempotency_key", ""), ) except (ValueError, backend_db.IdempotencyConflict) as error: actual = get_db(request).favorite_state(int(account["id"])) return render_r2_contract_state( request, route_id="software-favorites", requested_state="invalid", status_code=422, canonicalize_state=False, form_error=str(error), favorite_state=actual, ) except backend_db.StaleVersionError as error: actual = get_db(request).favorite_state(int(account["id"])) return render_r2_contract_state( request, route_id="software-favorites", requested_state="invalid", status_code=409, canonicalize_state=False, form_error=str(error), favorite_state=actual, ) return RedirectResponse( f"/favorites/software/{PRODUCT_ID}?state=" + ("present" if result["present"] else "removed"), 303, ) @app.post("/fixture/session") async def fixture_session(request: Request): if not fixture_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) values = await urlencoded_form(request) if values.get("csrf") != CSRF_VALUE: return render( request, "auth.html", page_title="Sign in to Capterra", next_path=safe_next(values.get("next")), csrf=CSRF_VALUE, auth_error="Your sign-in request expired. Please try again.", status_code=403, ) account_slug = values.get("account", PRIMARY_ACCOUNT_SLUG) if account_slug not in KNOWN_ACCOUNT_SLUGS: account_slug = PRIMARY_ACCOUNT_SLUG database = get_db(request) session_id = database.create_session(account_slug) response = RedirectResponse(safe_next(values.get("next")), status_code=303) response.set_cookie( SESSION_COOKIE, database.cookie_value(session_id), httponly=True, samesite="lax", secure=False, path="/", max_age=3600, ) return response @app.post("/fixture/sign-out") async def fixture_sign_out(request: Request) -> Response: if not fixture_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) get_db(request).delete_session_for_cookie( request.cookies.get(SESSION_COOKIE) ) response = RedirectResponse("/", status_code=303) response.delete_cookie(SESSION_COOKIE, path="/") return response @app.get("/reviews/notion/write", response_class=HTMLResponse) async def review_form(request: Request, state: str = "ready") -> HTMLResponse: account = current_account(request) if account is None: return render( request, "auth.html", page_title="Sign in to Capterra", next_path="/reviews/notion/write", csrf=CSRF_VALUE, unauthorized=True, status_code=401, ) draft = get_db(request).get_or_create_open_draft(account["id"]) normalized = ( state if state in {"ready", "fixture-error", "submitting", "no-submission"} else "ready" ) return render( request, "review_form.html", page_title="Review Notion", state=normalized, form_action=review_form_boundary(request)[0], csrf=review_form_boundary(request)[1], form_rating="", form_text="", focus_rating=False, draft_id=draft["id"], draft_version=draft["version"], errors=[], ) def _render_form_error( request: Request, *, status_code: int, errors: list[str], rating: str, text: str, draft, ) -> HTMLResponse: focus_rating = any( error == "Choose a whole-star rating between 1 and 5." for error in errors ) return render( request, "review_form.html", page_title="Review Notion", state="validation", form_action=review_form_boundary(request)[0], csrf=review_form_boundary(request)[1], form_rating=rating, form_text=text, focus_rating=focus_rating, draft_id=draft["id"] if draft is not None else "", draft_version=draft["version"] if draft is not None else 1, errors=errors, status_code=status_code, ) @app.post("/local/reviews/notion") @app.post("/fixture/reviews/notion", include_in_schema=False) async def submit_fixture_review(request: Request): fixture_request = request.url.path.startswith("/fixture/") if fixture_request and not fixture_boundary_authorized(request): return JSONResponse({"detail": "Not found"}, status_code=404) auth_token = request.cookies.get(AUTH_SESSION_COOKIE, "") auth_session = get_auth(request).resolve_session(auth_token) if fixture_request: account = current_account(request) else: account = ( current_account(request) if auth_session and auth_session.get("authenticated") else None ) if account is None: return RedirectResponse( "/auth/login?next=/reviews/notion/write", status_code=303 ) database = get_db(request) values = await urlencoded_form(request) rating = values.get("rating", "") text = values.get("review_text", "") csrf_valid = ( secrets.compare_digest(values.get("csrf", ""), CSRF_VALUE) if fixture_request else valid_auth_csrf(values, auth_token) ) if not csrf_valid: draft = database.get_or_create_open_draft(account["id"]) return _render_form_error( request, status_code=422, errors=["The local form expired. Reload and try again."], rating=rating, text=text, draft=draft, ) # Draft resolution: an explicit draft_id must exist and belong to the # session account; otherwise the account's open draft is used (created # on first POST when the form was never opened). draft_id = values.get("draft_id", "").strip() if draft_id: draft = database.get_draft(draft_id) if draft is None: return JSONResponse( {"ok": False, "error": "unknown draft"}, status_code=404 ) if draft["account_id"] != account["id"]: return JSONResponse( {"ok": False, "error": "draft belongs to another account"}, status_code=403, ) else: draft = database.get_or_create_open_draft(account["id"]) # Duplicate submission of the same draft is idempotent: reuse the row. existing = database.submission_for_draft(draft["id"]) if existing is not None: return RedirectResponse( f"/reviews/fixture-receipt/{RECEIPT_ID}", status_code=303 ) # Optimistic concurrency: a stale declared version conflicts. declared_version = values.get("draft_version", "").strip() if declared_version: try: declared = int(declared_version) except ValueError: declared = -1 if declared != int(draft["version"]): return _render_form_error( request, status_code=409, errors=[ "This draft changed in another tab (version conflict). " "Reload the form to continue from the latest draft." ], rating=rating, text=text, draft=draft, ) # Generic finite validation: any whole-star rating between 1 and 5 and # any text satisfying normalize_review_text is accepted. Benchmark seed # values are ordinary valid inputs, never a special case. errors: list[str] = [] try: rating_value: int | None = int(rating.strip()) except (AttributeError, ValueError): rating_value = None if rating_value is None or not 1 <= rating_value <= 5: errors.append("Choose a whole-star rating between 1 and 5.") normalized_text, text_errors = normalize_review_text(text) errors.extend(text_errors) # Every authorized, non-stale attempt is recorded as a draft revision # and bumps the draft version. database.record_revision(draft["id"], rating, text) if errors: refreshed = database.get_draft(draft["id"]) return _render_form_error( request, status_code=422, errors=errors, rating=rating, text=text, draft=refreshed, ) # One review per (reviewer, product): resubmitting the SAME finalized # draft stays idempotent (short-circuited above); an attempt to write # a second DISTINCT review for the same product is rejected with an # on-page conflict, mirroring the source site's one-review-per-product # rule. The DB backs this with UNIQUE(account_id, product_id) # (migration 4); DuplicateReviewError below is the constraint backstop. conflict_errors = [ "You have already reviewed this product. Capterra keeps " "one review per reviewer per product; your existing " "review is unchanged." ] if database.submission_for_pair( account["id"], draft["product_id"] ) is not None: return _render_form_error( request, status_code=409, errors=conflict_errors, rating=rating, text=text, draft=database.get_draft(draft["id"]), ) draft = database.get_draft(draft["id"]) try: database.create_submission(draft, rating_value, normalized_text) except backend_db.DuplicateReviewError: # Backstop: the UNIQUE (account, product) constraint fired (e.g. a # concurrent submit landed first). Same on-page conflict message. return _render_form_error( request, status_code=409, errors=conflict_errors, rating=rating, text=text, draft=database.get_draft(draft["id"]), ) return RedirectResponse( f"/reviews/fixture-receipt/{RECEIPT_ID}", status_code=303 ) @app.get( "/reviews/fixture-receipt/{receipt_code}", response_class=HTMLResponse ) async def fixture_receipt( request: Request, receipt_code: str ) -> HTMLResponse: account = current_account(request) if account is None: return RedirectResponse( "/auth/login?next=/reviews/notion/write", status_code=303 ) database = get_db(request) if receipt_code == RECEIPT_ID: own_submission = database.submission_for_pair( account["id"], PRODUCT_ID ) if own_submission is None: return RedirectResponse( "/reviews/notion/write?state=no-submission", status_code=303 ) return RedirectResponse( "/reviews/fixture-receipt/" f"{own_submission['receipt_code']}", status_code=303, ) submission = database.submission_for_receipt( account["id"], PRODUCT_ID, receipt_code ) if submission is None: return render( request, "receipt_unavailable.html", page_title="Receipt unavailable", status_code=404, ) return render( request, "receipt.html", page_title="Review submitted", submission_id=submission["id"], receipt_id=submission["receipt_code"], receipt_rating=int(submission["rating"]), receipt_text=submission["review_text"], ) # -- catalog-wide review writing ------------------------------------------ # Registered after the literal notion routes above; "notion" as a slug or # "186596" as a product id therefore never reaches these handlers. def _render_product_form_error( request: Request, *, product: Mapping[str, object], status_code: int, errors: list[str], rating: str, text: str, draft, ) -> HTMLResponse: token = request.cookies.get(AUTH_SESSION_COOKIE, "") return render( request, "product_review_form.html", status_code=status_code, page_title=f"Review {product['name']}", body_class="review-form-page", product=product, state="ready", form_action=f"/local/reviews/{product['id']}", csrf=auth_csrf(token) if token else "", form_rating=rating, form_text=text, focus_rating=any( error == "Choose a whole-star rating between 1 and 5." for error in errors ), draft_id=draft["id"] if draft is not None else "", draft_version=draft["version"] if draft is not None else 1, errors=errors, ) @app.get("/reviews/{product_slug}/write", response_class=HTMLResponse) async def product_review_form( request: Request, product_slug: str, state: str = "ready" ) -> Response: product = get_db(request).get_product_by_slug(product_slug) if product is None or not product.get("url_slug"): return render_public_replay("not-found", status_code=404) account = current_account(request) if account is None: return render( request, "auth.html", page_title="Sign in to Capterra", next_path=f"/reviews/{product_slug}/write", csrf=CSRF_VALUE, unauthorized=True, status_code=401, ) draft = get_db(request).get_or_create_open_draft( account["id"], str(product["id"]) ) token = request.cookies.get(AUTH_SESSION_COOKIE, "") return render( request, "product_review_form.html", page_title=f"Review {product['name']}", body_class="review-form-page", product=product, state=state if state in {"ready", "no-submission"} else "ready", form_action=f"/local/reviews/{product['id']}", csrf=auth_csrf(token) if token else "", form_rating="", form_text="", focus_rating=False, draft_id=draft["id"], draft_version=draft["version"], errors=[], ) @app.post("/local/reviews/{product_id}") async def submit_product_review(request: Request, product_id: str) -> Response: product = get_db(request).get_product(product_id) if product is None or not product.get("url_slug"): return JSONResponse({"detail": "Not Found"}, status_code=404) write_path = f"/reviews/{product['slug']}/write" auth_token = request.cookies.get(AUTH_SESSION_COOKIE, "") auth_session = get_auth(request).resolve_session(auth_token) account = ( current_account(request) if auth_session and auth_session.get("authenticated") else None ) if account is None: return RedirectResponse( f"/auth/login?next={write_path}", status_code=303 ) database = get_db(request) values = await urlencoded_form(request) rating = values.get("rating", "") text = values.get("review_text", "") if not valid_auth_csrf(values, auth_token): draft = database.get_or_create_open_draft(account["id"], product_id) return _render_product_form_error( request, product=product, status_code=422, errors=["The local form expired. Reload and try again."], rating=rating, text=text, draft=draft, ) draft_id = values.get("draft_id", "").strip() if draft_id: draft = database.get_draft(draft_id) if draft is None: return JSONResponse( {"ok": False, "error": "unknown draft"}, status_code=404 ) if draft["account_id"] != account["id"]: return JSONResponse( {"ok": False, "error": "draft belongs to another account"}, status_code=403, ) if draft["product_id"] != product_id: return JSONResponse( {"ok": False, "error": "draft belongs to another product"}, status_code=409, ) else: draft = database.get_or_create_open_draft(account["id"], product_id) existing = database.submission_for_draft(draft["id"]) if existing is not None: return RedirectResponse( f"/reviews/{product['slug']}/receipt/{existing['receipt_code']}", status_code=303, ) declared_version = values.get("draft_version", "").strip() if declared_version: try: declared = int(declared_version) except ValueError: declared = -1 if declared != int(draft["version"]): return _render_product_form_error( request, product=product, status_code=409, errors=[ "This draft changed in another tab (version conflict). " "Reload the form to continue from the latest draft." ], rating=rating, text=text, draft=draft, ) errors: list[str] = [] try: rating_value: int | None = int(rating.strip()) except (AttributeError, ValueError): rating_value = None if rating_value is None or not 1 <= rating_value <= 5: errors.append("Choose a whole-star rating between 1 and 5.") normalized_text, text_errors = normalize_review_text(text) errors.extend(text_errors) database.record_revision(draft["id"], rating, text) if errors: return _render_product_form_error( request, product=product, status_code=422, errors=errors, rating=rating, text=text, draft=database.get_draft(draft["id"]), ) conflict_errors = [ "You have already reviewed this product. Capterra keeps " "one review per reviewer per product; your existing " "review is unchanged." ] if database.submission_for_pair(account["id"], product_id) is not None: return _render_product_form_error( request, product=product, status_code=409, errors=conflict_errors, rating=rating, text=text, draft=database.get_draft(draft["id"]), ) draft = database.get_draft(draft["id"]) try: submission = database.create_submission( draft, rating_value, normalized_text ) except backend_db.DuplicateReviewError: return _render_product_form_error( request, product=product, status_code=409, errors=conflict_errors, rating=rating, text=text, draft=database.get_draft(draft["id"]), ) return RedirectResponse( f"/reviews/{product['slug']}/receipt/{submission['receipt_code']}", status_code=303, ) @app.get( "/reviews/{product_slug}/receipt/{receipt_code}", response_class=HTMLResponse, ) async def product_review_receipt( request: Request, product_slug: str, receipt_code: str ) -> Response: product = get_db(request).get_product_by_slug(product_slug) if product is None or not product.get("url_slug"): return render_public_replay("not-found", status_code=404) account = current_account(request) write_path = f"/reviews/{product_slug}/write" if account is None: return RedirectResponse( f"/auth/login?next={write_path}", status_code=303 ) submission = get_db(request).submission_for_receipt( account["id"], str(product["id"]), receipt_code ) if submission is None: return render( request, "receipt_unavailable.html", page_title="Receipt unavailable", status_code=404, ) return render( request, "receipt.html", page_title="Review submitted", product_name=product["name"], product_id=product["id"], write_path=write_path, reviews_path=f"/p/{product['id']}/{product['url_slug']}/reviews/", submission_id=submission["id"], receipt_id=submission["receipt_code"], receipt_rating=int(submission["rating"]), receipt_text=submission["review_text"], ) def main() -> None: inherited_fd = ( os.environ.get("WEBSITEBENCH_LISTEN_FD") or os.environ.get("CLAWBENCH_LISTEN_FD") ) if inherited_fd is not None: uvicorn.run(app, fd=int(inherited_fd), access_log=True) return port = int(os.environ.get("PORT", "8421")) uvicorn.run(app, host="127.0.0.1", port=port, access_log=True) if __name__ == "__main__": main()