diff --git "a/tasks/taskrabbit/solution/site/implementation/clone/app.py" "b/tasks/taskrabbit/solution/site/implementation/clone/app.py"
new file mode 100644--- /dev/null
+++ "b/tasks/taskrabbit/solution/site/implementation/clone/app.py"
@@ -0,0 +1,4175 @@
+"""TaskRabbit offline clone - R3 persistent backend.
+
+Local-only FastAPI + Jinja2 runtime backed by a site-local SQLite database
+(WAL mode) that lives outside clone/ (WEBSITEBENCH_DATA_DIR, default
+materials/taskrabbit/data). The server owns every business fact: booking
+categories, clients and their address books, the simulated Tasker roster
+with hourly rates, versioned availability slots derived from the frozen
+clock (2026-07-25T12:00:00-04:00) by date arithmetic, wizard drafts, and
+confirmed booking-request rows. Sessions are persisted server-side so
+login state survives a process restart.
+
+Generic source-site rules only: any syntactically valid US address is
+accepted, any seeded category/size/slot books identically, and no code
+path branches on a benchmark constant -- previously frozen values exist
+purely as ordinary seed rows. No real Tasker, payment, chat, SMS, or
+fulfillment is ever involved.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import hmac
+import json
+import mimetypes
+import os
+import re
+import sys
+from datetime import datetime
+from html.parser import HTMLParser
+from pathlib import Path
+from typing import Any, Iterator, Mapping
+from urllib.parse import parse_qs, quote, urljoin, urlsplit
+
+import uvicorn
+from fastapi import FastAPI, Request
+from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
+from fastapi.staticfiles import StaticFiles
+from fastapi.templating import Jinja2Templates
+from markupsafe import Markup, escape
+
+_CLONE_DIR = Path(__file__).resolve().parent
+if str(_CLONE_DIR) not in sys.path:
+ sys.path.insert(0, str(_CLONE_DIR))
+
+from backend import booking_payments # noqa: E402 (site-local package import)
+from backend import db # noqa: E402 (site-local package import)
+from backend import service_booking_catalog # noqa: E402
+from backend import task_catalog # noqa: E402 (site-local package import)
+from websitebench.local_clone_auth import ( # noqa: E402
+ AuthConflict,
+ AuthError,
+ AuthRateLimited,
+ AuthRejected,
+ AuthValidationError,
+ LocalAuthStore,
+ RESET_PUBLIC_MESSAGE,
+)
+from websitebench.public_clone_auth import ( # noqa: E402
+ VerificationUnavailable,
+ load_public_clone_registration_verification,
+)
+from websitebench.public_clone_auth.fastapi import ( # noqa: E402
+ consume_registration_ticket,
+ registration_script_response,
+ send_registration_code,
+ verify_registration_code,
+)
+from websitebench.site_backend import SiteBackend # noqa: E402
+from websitebench.site_backend.stripe_test import ( # noqa: E402
+ StripeTestError,
+ StripeTestGateway,
+ StripeTestLineItem,
+ StripeTestResponseError,
+ StripeTestUnavailable,
+)
+
+SITE_ID = "taskrabbit"
+_RUNTIME_PATH = Path(
+ os.environ.get(
+ "WEBSITEBENCH_SITE_BACKEND_RUNTIME",
+ _CLONE_DIR.parent / "backend" / "runtime.json",
+ )
+)
+_RUNTIME_VALUE = json.loads(_RUNTIME_PATH.read_text(encoding="utf-8"))
+if (
+ not isinstance(_RUNTIME_VALUE, dict)
+ or not isinstance(_RUNTIME_VALUE.get("site"), dict)
+ or _RUNTIME_VALUE["site"].get("id") != SITE_ID
+):
+ raise RuntimeError("Taskrabbit runtime site identity is inconsistent")
+SITE_BACKEND = SiteBackend.open(
+ _RUNTIME_VALUE,
+ data_root=db.resolve_data_dir(),
+ migration_hook=db.apply_migrations,
+ seed_hook=db.seed,
+)
+if SITE_BACKEND.config.site_id != SITE_ID:
+ raise RuntimeError("Taskrabbit runtime site identity is inconsistent")
+SITE_BACKEND.lifecycle.initialize()
+with db.session(SITE_BACKEND.lifecycle.database_path) as _metadata_connection:
+ _metadata_connection.execute(
+ f"PRAGMA user_version = {int(db.MIGRATIONS[-1][0])}"
+ )
+SESSION_COOKIE_CONFIG = SITE_BACKEND.session_cookie
+PUBLIC_REGISTRATION_VERIFICATION = load_public_clone_registration_verification()
+STAGE = "fullstack-candidate"
+VERSION = "taskrabbit-fullstack-2026-07-29.1"
+CANDIDATE_ID = "taskrabbit-v3-producer-candidate"
+FROZEN_CLOCK = db.FROZEN_CLOCK
+FROZEN_NOW = db.frozen_now()
+
+ASSETS_BASE = "/static/assets/source-current/2026-07-25"
+
+# Python's platform MIME database is not guaranteed to know WebP. Register
+# the frozen negotiated assets explicitly so the local runtime serves the
+# same media type recorded by the three browser captures.
+mimetypes.add_type("image/webp", ".webp")
+
+# Frozen anonymous source copy for the dedicated Furniture Assembly landing.
+# This is presentation-only data: the capture did not expose a furniture
+# booking form or any downstream booking effect.
+FURNITURE_CARDS = (
+ {
+ "slug": "furniture-assembly",
+ "detail_slug": "assemble-furniture",
+ "title": "Furniture Assembly",
+ "description": (
+ "Have a new desk or bookcase to put together? Taskers can assemble "
+ "any of your furniture—quickly and efficiently."
+ ),
+ "image": "furniture-icon-fygl4k4kujomneisofae.png",
+ },
+ {
+ "slug": "patio-furniture-assembly",
+ "detail_slug": "patio-furniture-assembly",
+ "title": "Patio Furniture Assembly",
+ "description": (
+ "Hire a Tasker to assemble your outdoor patio furniture. They'll "
+ "assemble everything and even haul away the old furniture."
+ ),
+ "image": "furniture-icon-yhfnwnv4ywgfrelmuwxj.png",
+ },
+ {
+ "slug": "desk-assembly",
+ "detail_slug": "desk-assembly",
+ "title": "Desk Assembly",
+ "description": (
+ "Working from home and need a desk assembled? Hire a Tasker to put "
+ "together your desk."
+ ),
+ "image": "furniture-icon-wll7emaxb0vvuktsnpml.webp",
+ },
+ {
+ "slug": "dresser-assembly",
+ "detail_slug": "dresser-assembly",
+ "title": "Dresser Assembly",
+ "description": (
+ "Taskers specialize in dresser assembly! No dresser is too big or "
+ "too small for Taskers to put together."
+ ),
+ "image": "furniture-icon-ifoacyypuu1pafnjmqkf.webp",
+ },
+ {
+ "slug": "bed-assembly",
+ "detail_slug": "bed-assembly",
+ "title": "Bed Assembly",
+ "description": (
+ "Hire a Tasker to assemble your bed. From bunk beds to sleigh beds, "
+ "Taskers can assemble it all! Same day available."
+ ),
+ "image": "furniture-icon-xbjdqfsh7wk8fzsvxcwr.webp",
+ },
+ {
+ "slug": "bookshelf-assembly",
+ "detail_slug": "bookshelf-assembly",
+ "title": "Bookshelf Assembly",
+ "description": (
+ "Hand a Tasker the instructions, they'll assemble your bookshelf "
+ "while you relax reading your book."
+ ),
+ "image": "furniture-icon-yuxk6sc90nycwnkh0ewr.webp",
+ },
+ {
+ "slug": "couch-assembly",
+ "detail_slug": "couch-assembly",
+ "title": "Couch Assembly",
+ "description": (
+ "Taskers can assemble almost any couch or sofa! They'll put together "
+ "your couch to your satisfaction."
+ ),
+ "image": "furniture-icon-hncwry8dmisdcr0ohxgc.webp",
+ },
+ {
+ "slug": "chair-assembly",
+ "detail_slug": "chair-assembly",
+ "title": "Chair Assembly",
+ "description": (
+ "Taskers can properly assemble your chair, allowing you to finally "
+ "get off your feet. Same day available."
+ ),
+ "image": "furniture-icon-yg2liw6sfatq9ax6aixf.webp",
+ },
+ {
+ "slug": "wardrobe-assembly",
+ "detail_slug": "wardrobe-assembly",
+ "title": "Wardrobe Assembly",
+ "description": (
+ "Wardrobe assembly can be complex and time consuming. Leave it to a "
+ "Tasker to complete the project to your satisfaction."
+ ),
+ "image": "furniture-icon-pngd8skczfsmu2vjp6ak.webp",
+ },
+ {
+ "slug": "table-assembly",
+ "detail_slug": "table-assembly",
+ "title": "Table Assembly",
+ "description": (
+ "Need table assembly services? Taskers can assemble a table in a "
+ "snap and save you the hassle."
+ ),
+ "image": "furniture-icon-kcmkm9k4hbeg3rqcthyo.webp",
+ },
+ {
+ "slug": "disassemble-furniture",
+ "detail_slug": "furniture-disassembly",
+ "title": "Disassemble furniture",
+ "description": "If you need help taking furniture apart, Tasker can help!",
+ "image": "furniture-icon-zgxyiicd1pjn1gjyfnbd.webp",
+ },
+)
+
+# Current source-backed content for the Furniture Assembly service-detail
+# pages captured on 2026-08-08. The upstream pages share a stable shell but
+# deliberately vary in depth: chair/table have no article or FAQ module, while
+# the remaining pages expose the modules represented below.
+FURNITURE_DETAIL_ASSETS_BASE = (
+ "/static/assets/source-current/2026-08-08-furniture-detail"
+)
+
+FURNITURE_DETAIL_CONTENT: dict[str, dict[str, Any]] = {
+ "assemble-furniture": {
+ "hero_title": "Furniture Assembly",
+ "hero_description": (
+ "Need someone to put together furniture? Hire a Tasker to assemble "
+ "your furniture and leave the building to them."
+ ),
+ "hero_image": "hero-assemble-furniture.webp",
+ "body_title": "Furniture Assembly Services",
+ "body_image": "body-assemble-furniture.webp",
+ "body_html": """
+
Let's be honest: you were never going to read that furniture assembly manual. Taskers on Taskrabbit will come to your home and assemble your furniture for you! Taskers frequently assemble beds, bunk beds, dressers, desks, couches, tables, chairs, wardrobes, and more.
+Taskers bring their own tools for quick, efficient assembly, with options for furniture disassembly and furniture removal as well.
+Official IKEA Assembly Partner
+As official furniture assembly partners with IKEA, Taskers are familiar with popular collections like MALM, KALLAX, and HEMNES. Fill your space with exactly what you want, no matter how complex the furniture is.
+Furniture assembly doesn't need to be a hassle. Taskers will put together furniture in a snap and save you time and effort. Just task!
+What furniture can Taskers assemble?
+With a reliable Tasker, you can go from box to beautifully assembled in no time:
+- For the living room: Couches, coffee tables, TV stands, and shelving units.
- For the bedroom: Bed frames, dressers, nightstands, and wardrobes.
- For the office: Desks, office chairs, and bookcases.
- And everywhere else: Patio furniture, dining sets, and play equipment.
+Why choose Taskrabbit for furniture assembly?
+Your weekend is too valuable to spend wrestling with confusing instruction manuals. Professional assembly means getting it done right the first time.
+- Save your time: What might take you hours, a Tasker can finish quickly.
- Skip the stress: Avoid the frustration that comes with DIY projects.
- Ensure it's built to last: Taskers make sure every piece is stable, secure, and ready for use.
- No tools? No problem: Your Tasker arrives with everything needed.
+""",
+ "cta_label": "Find help now",
+ "location_label": "Furniture Assembly",
+ "faqs": (
+ "How much does furniture assembly cost?",
+ "How long does furniture assembly typically take?",
+ "Do Taskers bring their own tools for furniture assembly?",
+ ),
+ },
+ "patio-furniture-assembly": {
+ "hero_title": "Patio Set Assembly",
+ "hero_description": (
+ "Hire a Tasker for patio furniture assembly or to haul away the old furniture."
+ ),
+ "hero_image": "hero-patio-furniture-assembly.webp",
+ "body_title": "Patio Furniture Assembly Services",
+ "body_image": "body-patio-furniture-assembly.webp",
+ "body_html": """
+Patio furniture assembly can be a daunting task in terms of how many pieces there are to put together, how large and heavy the furniture can be, and how much time it will take to do it alone. Scheduling patio furniture assembly is easier than ever thanks to Taskers who are nearby and eager to help.
+Taskers can also help you move patio furniture for when you want to store it for winter, or bring it back out when you’re ready to enjoy the warmer months. Or if your outdoor furniture is to stay outdoors, get in touch with a Tasker for help with patio furniture cleaning services.
+Whether it’s a lounge chair, a complete patio set, or even a porch swing, a Tasker can help you put together any and all patio furniture, weatherproof it, and haul away any unwanted items! Hire a Tasker for patio furniture assembly today, and get the task done in a snap.
+""",
+ "cta_label": "Find Help Now",
+ "location_label": "Patio Set Assembly",
+ "faqs": (
+ "How much does it cost to assemble patio furniture?",
+ "Will my porch hold a swing?",
+ "How do you weatherproof outdoor wood furniture?",
+ "Is rattan furniture easy to assemble?",
+ ),
+ },
+ "desk-assembly": {
+ "hero_title": "Desk Assembly",
+ "hero_description": (
+ "Need desk assembly services? Hire a Tasker, and get your furniture set up in a snap."
+ ),
+ "hero_image": "hero-desk-assembly.webp",
+ "body_title": "Desk Assembly Service",
+ "body_image": "body-desk-assembly.webp",
+ "body_html": """
+Whether you're upgrading your workspace, finally tackling that spare room, or just need a proper place to answer emails, desk assembly doesn't have to be a weekend-ruining project. With Taskrabbit, you can hire a Tasker for desk assembly and get your space set up in a flash.
+Taskers can help assemble almost any piece of furniture you have. Just hand them the instructions, and let them work their magic. Taskers can help get that desk out of its box and into the office you've been dreaming of.
+Take the hassle out of creating your workspace by finding reliable desk assembly services near you.
+Why hire a Tasker for desk assembly
Hiring a desk assembly service saves time, prevents frustration, and ensures your furniture is built correctly the first time. Skip the confusing instructions and relationship-testing afternoons.
Here's why hiring a Tasker makes sense:
+- Right tools: Taskers arrive with the equipment you need, so no worry about if you have the right size screwdriver
- Experience: They've decoded those hieroglyphic instructions countless times
- Time savings: Keep your weekend for actually enjoying your new workspace
+Types of desks Taskers assemble
Taskers can assemble any type of desk, no matter the complexity or retailer:
+- L-shaped corner desks for maximizing small spaces
- Standing desks with adjustable heights
- Gaming desks with multi-level surfaces and cable management
- Executive desks with drawers and filing systems
- Simple writing desks for basic home offices
- IKEA desks and products from any major retailer
+""",
+ "cta_label": "Book Now",
+ "location_label": "Desk Assembly",
+ "faqs": (
+ "How much does desk assembly cost?",
+ "When can I get desk assembly service?",
+ "Do Taskers handle cleanup after assembly?",
+ ),
+ },
+ "dresser-assembly": {
+ "hero_title": "Dresser Assembly",
+ "hero_description": "Taskers specialize in dresser assembly! No dresser is too big or too small to put together. Find help now.",
+ "hero_image": "hero-dresser-assembly.webp",
+ "body_title": "Dresser Assembly Services",
+ "body_image": "body-dresser-assembly.webp",
+ "body_html": """
+Think of Taskers as your magic dresser assembly fairies. With a few clicks in the app, you'll browse and book a Tasker. Then, before you know it, you'll have a brand new dresser—and a lovely new place for your clothes to call home.
+Taskers specialize in all types of furniture assembly, from simple pieces to large, complex ones. Instead of spending all afternoon dealing with dresser setup, consider hiring a Tasker to put it together instead. With help from a Tasker, you can get back to enjoying what really matters, like hobbies or time with your family and friends.
+Taskers can make dresser assembly a breeze, so don't do it all yourself. Just task!
+""",
+ "body_image_first": True,
+ "cta_label": "Book Now",
+ "location_label": "Dresser Assembly",
+ "faqs": (
+ "When can I get my dresser assembled?",
+ "How much does it cost to assemble a dresser?",
+ "Do I need to provide Taskers with tools to assemble my dresser?",
+ "I started to assemble my dresser and gave up. Can someone help me?",
+ ),
+ },
+ "bed-assembly": {
+ "hero_title": "Bed Assembly",
+ "hero_description": "Hire a Tasker to assemble your bed. From bunk beds to sleigh beds, Taskers can do it all! Same-day assembly available.",
+ "hero_image": "hero-bed-assembly.webp",
+ "body_title": "Bed Assembly and Installation",
+ "body_image": "body-bed-assembly.webp",
+ "body_html": """
+They say you should get a new mattress every seven years, but what about your bed? While there may not be a handy guide for when to replace a bed, you know the time has come. Whether you're finally upgrading to the king-size you've been dreaming of, you've decided you're too old to be sleeping on a mattress on the floor, or your baby is graduating to a big-kid bed, assembling a bed frame is in your future.
+Now that you've picked out the perfect bed, it's time to get down to business and embrace that bed assembly. But maybe you've got a full plate, or you aren't the handy type. What to do? Why, hire a Tasker, of course! With just a few clicks, you'll be catching the restorative Zzzs you've been after.
+Hire a Tasker for bed assembly, including bunk bed assembly, pull-out bed assembly, and more. Don't do it all yourself. Just task.
+""",
+ "cta_label": "Book Now",
+ "location_label": "Bed Assembly",
+ "faqs": (
+ "What are the 3 parts of a bed?",
+ "When can I get my new bed assembled?",
+ "How much does it cost to assemble a bed?",
+ "Can Taskers help with bunk bed assembly?",
+ ),
+ },
+ "bookshelf-assembly": {
+ "hero_title": "Bookshelf Assembly",
+ "hero_description": "Need bookshelf assembly services? Hand the instructions to a Tasker, and let them take care of it. Find the help you need today!",
+ "hero_image": "hero-bookshelf-assembly.webp",
+ "body_title": "Find Bookshelf Assembly Services Near You",
+ "body_image": "body-bookshelf-assembly.webp",
+ "body_html": """
+Bookshelf assembly has become even more necessary as we spend more time at home. Books can be a fantastic escape or even a way to learn new and valuable skills. It's important to have a place for all those books, and that's where Taskers come in.
+Taskers are skilled in bookshelf assembly and have the tools needed to get the job done in a snap. Efficiency is a key part of hiring a Tasker, as they're often able to put together furniture quickly and expertly. Taskers can even help mount the shelves to your wall!
+Don't waste your afternoon fumbling around with the small parts and pieces. Instead, just task.
+""",
+ "cta_label": "Book Now",
+ "location_label": "Bookshelf Assembly",
+ "faqs": (),
+ },
+ "couch-assembly": {
+ "hero_title": "Couch Assembly",
+ "hero_description": "Taskers are available for couch and sofa assembly! Hire a Tasker to put your new furniture together in a snap.",
+ "hero_image": "hero-couch-assembly.webp",
+ "body_title": "Couch Assembly & Installation",
+ "body_image": "body-couch-assembly.webp",
+ "body_html": """
+The couch (or sofa) is the real workhorse of the home. It's where we nap, snuggle our kiddos while watching cartoons, or spend far too many hours binging the latest hit TV show. Now that we're all spending a lot more time at home, your couch can even double as our work-from-home seat of choice.
+So, whether you call it a couch or a sofa, there's no time like the present to upgrade to a cozier one. But what to do when the couch or sofa of your dreams—that future Saturday lounge location—needs assembly? Never fear, Taskers are here. With a few clicks in our app, you'll have it put together and be relaxing in no time.
+Hire a Tasker today, whether it's to put your couch together or to remove it (so you can get one that's a little comfier). There's no need to do it all on your own! Instead, just task.
+""",
+ "cta_label": "Book Now",
+ "location_label": "Couch Assembly",
+ "faqs": (
+ "How long does it take to assemble a couch?",
+ "When can I get my couch assembled?",
+ "How much does couch assembly cost?",
+ "Can Taskers help with a sleeper sofa installation?",
+ ),
+ },
+ "chair-assembly": {
+ "hero_title": "Chair Assembly",
+ "hero_description": "Taskers can provide chair assembly services, allowing you to finally get off your feet. Same-day service available.",
+ "hero_image": "hero-chair-assembly.webp",
+ "cta_label": "Book Now",
+ "location_label": "Chair Assembly",
+ "faqs": (),
+ },
+ "wardrobe-assembly": {
+ "hero_title": "Wardrobe Assembly",
+ "hero_description": "Wardrobe assembly can be complex and time consuming. Leave it to a Tasker to complete the project to your satisfaction.",
+ "hero_image": "hero-wardrobe-assembly.webp",
+ "body_title": "Wardrobe Assembly Services",
+ "body_image": "body-wardrobe-assembly.webp",
+ "body_html": """
+Wardrobe assembly and installation can be time consuming, stressful and complicated. There are often a lot of different pieces, small parts and complex instructions to follow. If you've ever found yourself struggling to assemble a closet or wardrobe, then Taskrabbit might be for you.
+Taskers are experienced with wardrobe assembly and are available to help at a price that works for your budget. Many Taskers have assembled IKEA furniture and some can even put together unique wardrobes that require power tools or custom assembly.
+Find wardrobe installers near you and take the hassle out of wardrobe assembly! Don't do it all on your own. Just task.
+""",
+ "cta_label": "Book Now",
+ "location_label": "Wardrobe Assembly",
+ "faqs": (),
+ },
+ "table-assembly": {
+ "hero_title": "Table Assembly",
+ "hero_description": "Taskers can assemble a table in the blink of an eye. Same-day table assembly available.",
+ "hero_image": "hero-table-assembly.webp",
+ "cta_label": "Book Now",
+ "location_label": "Table Assembly",
+ "faqs": (),
+ },
+ "furniture-disassembly": {
+ "hero_title": "Disassemble Furniture",
+ "hero_description": "If you need help taking furniture apart, Tasker can help! They'll disassemble your furniture and put it back together for you.",
+ "hero_image": "hero-furniture-disassembly.webp",
+ "body_title": "Furniture Disassembly Services",
+ "body_image": "body-furniture-disassembly.webp",
+ "body_html": """
+Furniture disassembly service involves professionally taking apart furniture for moves, storage, disposal, or reassembly. Taskers handle everything from bed frames and wardrobes to sectionals and dining sets.
Here's what you get when you book with Taskrabbit:
+- Complete disassembly service: For moves, downsizing, remodeling, and disposal
- Background-checked Taskers: Vetted professionals with quality focus
- Flexible pricing: Rates that fit your budget
+You could try to remember how that IKEA dresser came together... in reverse. Or you could book a Tasker and save yourself the headache.
+When you need furniture disassembly
Let's be real: sometimes furniture needs to come apart. Here are the most common situations:
+- Moving: When that sectional won't pivot up the stairs
- Downsizing: Fitting your life into a smaller space
- Storage: Preparing furniture for long-term storage
- Disposal: Getting bulky items out the door for good
A Tasker can handle the disassembly so you don't have to.
+""",
+ "cta_label": "Find Help Now",
+ "location_label": "Disassemble Furniture",
+ "faqs": (
+ "How quickly can I get help with furniture disassembly?",
+ "How much does furniture disassembly cost?",
+ "Can Taskers handle furniture transport?",
+ "What types of furniture can Taskers disassemble?",
+ "Do Taskers bring their own tools for disassembly?",
+ ),
+ },
+}
+
+FURNITURE_DETAIL_STEPS = (
+ ("Describe Your Task", "Tell us what you need done, when and where it works for you.", "how-step-1.webp"),
+ ("Choose Your Tasker", "Browse trusted Taskers by skills, reviews, and price. Chat with them to confirm details.", "how-step-2.webp"),
+ ("Get It Done!", "Your Tasker arrives and gets the job done. Pay securely and leave a review, all through Taskrabbit.", "how-step-3.webp"),
+)
+
+FURNITURE_DETAIL_CITIES = (
+ "New York City", "Los Angeles", "San Francisco", "Orange County", "Atlanta",
+ "Fort Worth", "Dallas", "Houston", "Philadelphia", "San Diego", "Portland",
+ "Phoenix", "St. Petersburg", "Tampa", "Las Vegas", "Orlando", "Baltimore",
+ "Chicago", "Washington DC", "Austin", "Miami", "Boston", "Seattle", "Denver",
+ "Berkeley", "San Jose", "Oakland",
+)
+
+FURNITURE_STEPS = (
+ {
+ "title": "Select your Tasker",
+ "description": (
+ "Describe your task and choose a background checked and "
+ "client-reviewed Tasker for the job"
+ ),
+ },
+ {
+ "title": "Schedule a time",
+ "description": "Get your task done — on your time",
+ },
+ {
+ "title": "Pay when it’s done",
+ "description": (
+ "Pay seamlessly through the TaskRabbit platform only after your "
+ "task is complete"
+ ),
+ },
+)
+
+FURNITURE_REVIEWS = (
+ {
+ "quote": (
+ "Kai showed up early, was quick, professional and did an overall "
+ "great job. He is smart and trust worthy and I would highly "
+ "reccomend him to build furniture."
+ ),
+ "author": "Jameeleh S.",
+ "image": "review-avatar-bpw52tibin9k3t1dnnck.webp",
+ },
+ {
+ "quote": (
+ "On time, friendly, great job, organized the pieces of my bed frame "
+ "so that they are ready to go for the movers, and efficient. I'll "
+ "definitely book Aaron again."
+ ),
+ "author": "Katiti C.",
+ "image": "review-avatar-metkvbuqzd7hcjwy9sfm.webp",
+ },
+ {
+ "quote": (
+ "100% professional & reliable. Rolando is an excellent tasker. "
+ "Highly recommended."
+ ),
+ "author": "Gregory G.",
+ "image": "review-avatar-qvxdo2jfnbwmqw2o6xry.webp",
+ },
+)
+
+FURNITURE_FAQS = (
+ {
+ "id": "can-hire-assembly",
+ "question": "Can I hire someone to put something together?",
+ "answer_before_link": (
+ "Absolutely! Taskrabbit can connect you with handy Taskers who "
+ "are experienced in all kinds of "
+ ),
+ "related_label": "furniture assembly",
+ "related_href": "/near-me/assemble-furniture",
+ "answer_after_link": (
+ ", including beds, dressers, IKEA furniture, and outdoor patio "
+ "furniture. Taskers can bring their own tools to assemble your "
+ "furniture and move it just where you need it."
+ ),
+ },
+ {
+ "id": "assembly-duration",
+ "question": "How long does it take to assemble furniture?",
+ "answer": (
+ "Furniture assembly typically takes between 1-4 hours depending "
+ "on the size and complexity of the furniture."
+ ),
+ },
+ {
+ "id": "tools",
+ "question": (
+ "Do I need to provide tools to Taskers for furniture assembly?"
+ ),
+ "answer": (
+ "Generally, Taskers provide their own equipment, but it helps to "
+ "confirm with them prior to the job whether they have the right "
+ "tools. If your furniture assembly job requires power tools, be "
+ "sure to let your Tasker know beforehand if possible."
+ ),
+ },
+)
+
+FURNITURE_OTHER_TASKS = (
+ {"label": "Painting", "href": "/services/handyman/painting"},
+ {"label": "TV Mounting", "href": "/services/handyman/wall-mount-tv"},
+ {"label": "Wallpapering Service", "href": "/services/handyman/wallpapering"},
+ {"label": "Moving Services", "href": "/services/moving"},
+ {"label": "Handyman", "href": "/services/handyman"},
+ {"label": "Yardwork", "href": "/services/yardwork-removal"},
+)
+
+FURNITURE_RELATED_TASKS = {
+ task["href"]: task
+ for task in FURNITURE_OTHER_TASKS
+ if task["href"] != "/services/moving"
+}
+
+# ---------------------------------------------------------------------------
+# Honest destinations for controls whose source target was never observed
+# ---------------------------------------------------------------------------
+#
+# `scope/routes.json` classifies these controls `honest-placeholder` with
+# `destination_evidence_kind: "unavailable"`: the capture proves the control
+# exists on the source page, but never recorded where it leads. Rendering them
+# as `aria-disabled` spans made them unreachable, which reads as "not built"
+# rather than "not observed" — the AS-1 defect. Rendering a guessed href would
+# be worse: it would state a destination the capture does not support.
+#
+# So each one is a real link to a local page that says exactly that. The
+# control is keyboard reachable, works with no JavaScript, and claims nothing
+# the evidence does not carry. Anything genuinely modelled here links to the
+# real local route instead and never appears in this map.
+EXTERNAL_DESTINATION_NOTE = (
+ "This service catalog records that the control exists on the Taskrabbit "
+ "page it was captured from, but the capture never followed it, so its "
+ "destination is unknown here."
+)
+
+def _placeholder(label: str, return_path: str = "/services") -> dict[str, str]:
+ return {"label": label, "description": EXTERNAL_DESTINATION_NOTE,
+ "return_path": return_path}
+
+
+EXTERNAL_DESTINATIONS: dict[str, dict[str, str]] = {
+ # Persistent chrome — header and footer, present on every page.
+ "become-a-tasker": _placeholder("Become a Tasker", "/"),
+ "services-by-city": _placeholder("Services By City"),
+ "services-nearby": _placeholder("Services Nearby"),
+ "cost-guides-by-category": _placeholder("Cost Guides By Category"),
+ "elite-taskers": _placeholder("Elite Taskers"),
+ "help": _placeholder("Help", "/"),
+ "about-us": _placeholder("About Us", "/"),
+ "careers": _placeholder("Careers", "/"),
+ "partner-with-taskrabbit": _placeholder("Partner with Taskrabbit", "/"),
+ "press": _placeholder("Press", "/"),
+ "taskrabbit-for-good": _placeholder("Taskrabbit for Good", "/"),
+ "blog": _placeholder("Blog", "/"),
+ "terms": _placeholder("Terms", "/"),
+ "privacy": _placeholder("Privacy", "/"),
+ "terms-and-privacy": _placeholder("Terms & Privacy", "/"),
+ "california-consumer-notice": _placeholder("California Consumer Notice", "/"),
+ "do-not-sell-my-personal-information": _placeholder(
+ "Do Not Sell My Personal Information", "/"
+ ),
+ "legal": _placeholder("Legal", "/"),
+ # Moving services whose own booking flow was never captured. Help Moving
+ # is modelled end to end and links to /book/help-moving instead.
+ "truck-assisted-help-moving": _placeholder(
+ "Truck Assisted Help Moving", "/services/moving"
+ ),
+ "packing-services-and-help": _placeholder(
+ "Packing Services & Help", "/services/moving"
+ ),
+ "unpacking-services": _placeholder("Unpacking Services", "/services/moving"),
+ "full-service-help-moving": _placeholder(
+ "Full Service Help Moving", "/services/moving"
+ ),
+ "local-movers": _placeholder("Local Movers", "/services/moving"),
+ "furniture-movers": _placeholder("Furniture Movers", "/services/moving"),
+ "in-home-furniture-movers": _placeholder(
+ "In-Home Furniture Movers", "/services/moving"
+ ),
+ "heavy-furniture-moving": _placeholder(
+ "Heavy Furniture Moving", "/services/moving"
+ ),
+ "moving-office-furniture": _placeholder(
+ "Moving Office Furniture", "/services/moving"
+ ),
+ "office-movers": _placeholder("Office Movers", "/services/moving"),
+ "one-item-movers": _placeholder("One Item Movers", "/services/moving"),
+ "pool-table-movers": _placeholder("Pool Table Movers", "/services/moving"),
+ "storage-unit-moving": _placeholder("Storage Unit Moving", "/services/moving"),
+ "rearranging-furniture": _placeholder(
+ "Rearranging Furniture", "/services/moving"
+ ),
+ "heavy-lifting": _placeholder("Heavy Lifting", "/services/moving"),
+ "deliver-big-piece-of-furniture": _placeholder(
+ "Deliver Big Piece of Furniture", "/services/moving"
+ ),
+ "mattress-pick-up-and-removal": _placeholder(
+ "Mattress Pick-Up & Removal", "/services/moving"
+ ),
+ "couch-removal": _placeholder("Couch Removal", "/services/moving"),
+ "furniture-removal": _placeholder("Furniture Removal", "/services/moving"),
+ "appliance-removal": _placeholder("Appliance Removal", "/services/moving"),
+ # Category chips whose landing page was never captured.
+ "junk-pickup": _placeholder("Junk Pickup", "/services/moving"),
+ "move-in-cleaning": _placeholder("Move In Cleaning"),
+ "spring-cleaning": _placeholder("Spring Cleaning"),
+ "plumbing": _placeholder("Plumbing"),
+ "hang-art-mirror-and-decor": _placeholder("Hang Art, Mirror & Decor"),
+ "electrical-help": _placeholder("Electrical Help"),
+ "wait-in-line": _placeholder("Wait in Line"),
+ "closet-organization-service": _placeholder("Closet Organization Service"),
+}
+
+# The searchable service index. Routes the clone models end to end come first
+# and keep their real destination; everything else resolves to the honest
+# destination declared above, so a search result never promises more than the
+# capture supports.
+MODELLED_SERVICES: tuple[dict[str, str], ...] = (
+ {"label": "Help Moving", "href": "/services/moving"},
+ {"label": "Moving Services", "href": "/services/moving"},
+ {"label": "Furniture Assembly", "href": "/services/furniture-assembly"},
+ {"label": "Handyman", "href": "/services/handyman"},
+ {"label": "Home Repairs", "href": "/services/handyman"},
+ {"label": "Painting", "href": "/services/handyman/painting"},
+ {"label": "TV Mounting", "href": "/services/handyman/wall-mount-tv"},
+ {"label": "Wallpapering Service", "href": "/services/handyman/wallpapering"},
+ {"label": "Yardwork", "href": "/services/yardwork-removal"},
+ {"label": "Yard Work Services", "href": "/services/yardwork-removal"},
+ {
+ "label": "Furniture Assembly Near You",
+ "href": "/near-me/assemble-furniture",
+ },
+)
+
+_SERVICES_CATALOG_VALUE = json.loads(
+ (_CLONE_DIR / "frontend" / "services_catalog.json").read_text(
+ encoding="utf-8"
+ )
+)
+if (
+ _SERVICES_CATALOG_VALUE.get("schema_version")
+ != "websitebench.taskrabbit.services-catalog.v1"
+):
+ raise RuntimeError("Taskrabbit services catalog schema is inconsistent")
+SERVICE_GROUPS: tuple[dict[str, Any], ...] = tuple(
+ _SERVICES_CATALOG_VALUE["groups"]
+)
+SERVICE_CATALOG_BY_PATH: dict[str, dict[str, Any]] = {}
+for _group in SERVICE_GROUPS:
+ SERVICE_CATALOG_BY_PATH[str(_group["href"])] = {
+ "kind": "group",
+ "label": str(_group["label"]),
+ "href": str(_group["href"]),
+ "group": _group,
+ }
+ for _service in _group["services"]:
+ SERVICE_CATALOG_BY_PATH[str(_service["href"])] = {
+ "kind": "service",
+ "label": str(_service["label"]),
+ "href": str(_service["href"]),
+ "group": _group,
+ }
+_SERVICE_DIRECTORY_PATHS = frozenset(SERVICE_CATALOG_BY_PATH)
+
+_SERVICE_PAGES_VALUE = json.loads(
+ (_CLONE_DIR / "frontend" / "service_pages.json").read_text(
+ encoding="utf-8"
+ )
+)
+if (
+ _SERVICE_PAGES_VALUE.get("schema_version")
+ != "websitebench.taskrabbit.service-pages.v1"
+ or _SERVICE_PAGES_VALUE.get("directory_page_count") != 211
+ or _SERVICE_PAGES_VALUE.get("recursive_page_count") != 87
+ or _SERVICE_PAGES_VALUE.get("expected_page_count") != 298
+ or not isinstance(_SERVICE_PAGES_VALUE.get("pages"), dict)
+):
+ raise RuntimeError("Taskrabbit service page catalog schema is inconsistent")
+if service_booking_catalog.CATALOG.get("source_pages_sha256") != (
+ _SERVICE_PAGES_VALUE.get("source_pages_sha256")
+):
+ raise RuntimeError("Taskrabbit service booking catalog is stale")
+SERVICE_PAGES_BY_PATH: dict[str, dict[str, Any]] = dict(
+ _SERVICE_PAGES_VALUE["pages"]
+)
+if (
+ len(SERVICE_PAGES_BY_PATH) != 298
+ or not _SERVICE_DIRECTORY_PATHS <= set(SERVICE_PAGES_BY_PATH)
+):
+ raise RuntimeError("Taskrabbit service page coverage is incomplete")
+for _path, _page in SERVICE_PAGES_BY_PATH.items():
+ _catalog_entry = SERVICE_CATALOG_BY_PATH.get(_path)
+ _expected_family = (
+ "marketing-group"
+ if (_catalog_entry or _page).get("kind") == "group"
+ else "service-detail"
+ )
+ if (
+ _page.get("family") != _expected_family
+ or (
+ _catalog_entry is not None
+ and _page.get("kind") != _catalog_entry["kind"]
+ )
+ or not isinstance(_page.get("bff"), dict)
+ ):
+ raise RuntimeError(f"Taskrabbit service page family is inconsistent: {_path}")
+ if _catalog_entry is None:
+ _group = {
+ "label": str(_page.get("group_label") or "Services"),
+ "href": str(_page.get("group_path") or "/services"),
+ "services": [],
+ }
+ _catalog_entry = {
+ "kind": str(_page["kind"]),
+ "label": str(_page["label"]),
+ "href": _path,
+ "group": _group,
+ }
+ SERVICE_CATALOG_BY_PATH[_path] = _catalog_entry
+ _catalog_entry["page"] = _page
+
+
+def _service_text_key(value: str) -> str:
+ return " ".join(re.sub(r"[^a-z0-9]+", " ", value.casefold()).split())
+
+
+_SERVICE_BOOKING_HREFS = {
+ _service_text_key(str(task["label"])): str(task["booking_href"])
+ for task in task_catalog.TASKS
+}
+_SERVICE_BOOKING_HREFS.update(
+ {
+ "furniture assembly": "/book/furniture-assembly/furniture-assembly",
+ "deep cleaning": "/book/task/deep-clean",
+ "house cleaning services": "/book/task/cleaning",
+ "home apartment cleaning": "/book/task/cleaning",
+ "move out cleaning": "/book/task/move-out-clean",
+ "truck assisted help moving": "/book/task/truck-assisted-help-moving",
+ "heavy lifting": "/book/task/heavy-lifting-loading",
+ "rearranging furniture": "/book/task/rearrange-furniture",
+ "furniture removal": "/book/task/trash-furniture-removal",
+ "junk pickup": "/book/task/junk-haul-away",
+ "yard work services": "/book/task/yard-work",
+ "yardwork services": "/book/task/yard-work",
+ "gardening services": "/book/task/gardening-weeding",
+ "weed removal": "/book/task/gardening-weeding",
+ "hedge trimming service": "/book/task/branch-hedge-trimming",
+ "plumbing": "/book/task/plumbing-help",
+ "painting": "/book/task/indoor-painting",
+ "wallpapering service": "/book/task/wallpapering",
+ "general mounting": "/book/task/other-mounting",
+ "install shelves rods hooks": "/book/task/install-shelves-rods-hooks",
+ }
+)
+
+
+def service_cta_href(label: str) -> str:
+ """Return a local booking entry without inventing unsupported effects."""
+ return _SERVICE_BOOKING_HREFS.get(
+ _service_text_key(label),
+ "/auth/login?next=/dashboard",
+ )
+
+
+def service_booking_href(source_cta: str) -> str:
+ """Translate one frozen source CTA to its exact local task identity."""
+ task = service_booking_catalog.task_from_source_cta(source_cta)
+ if task is None:
+ raise RuntimeError(f"Unbound Taskrabbit service CTA: {source_cta}")
+ return str(task["booking_href"])
+
+
+def service_source_title(value: str) -> str:
+ """Strip the shared source brand because base.html appends it once."""
+ return re.sub(r"\s+[|\-]\s+TaskRabbit.*$", "", value, flags=re.IGNORECASE)
+
+
+def _service_local_href(value: str) -> str | None:
+ raw = value.strip()
+ if not raw:
+ return None
+ # Contentful occasionally emits deeply relative service links. Resolve
+ # them against the source root, then keep only destinations the clone owns.
+ marker = raw.find("services/")
+ if marker >= 0 and not raw.startswith(("http://", "https://", "/")):
+ raw = "/" + raw[marker:]
+ resolved = urlsplit(urljoin("https://www.taskrabbit.com/", raw))
+ if resolved.hostname not in {"taskrabbit.com", "www.taskrabbit.com"}:
+ return None
+ path = resolved.path.rstrip("/") or "/"
+ if path in SERVICE_PAGES_BY_PATH or path in {
+ "/services",
+ "/services/help-moving",
+ "/near-me/assemble-furniture",
+ }:
+ return path
+ return None
+
+
+class _ServiceHtmlSanitizer(HTMLParser):
+ """Small allowlist sanitizer for captured public marketing prose."""
+
+ _TAGS = {"p", "br", "strong", "em", "b", "i", "ul", "ol", "li", "h2", "h3"}
+
+ def __init__(self) -> None:
+ super().__init__(convert_charrefs=True)
+ self.parts: list[str] = []
+ self.links: list[bool] = []
+
+ def handle_starttag(
+ self, tag: str, attrs: list[tuple[str, str | None]]
+ ) -> None:
+ tag = tag.casefold()
+ if tag == "a":
+ href = _service_local_href(
+ next((value or "" for key, value in attrs if key == "href"), "")
+ )
+ self.links.append(href is not None)
+ if href is not None:
+ self.parts.append(f'')
+ return
+ if tag in self._TAGS:
+ self.parts.append("
" if tag == "br" else f"<{tag}>")
+
+ def handle_startendtag(
+ self, tag: str, attrs: list[tuple[str, str | None]]
+ ) -> None:
+ self.handle_starttag(tag, attrs)
+
+ def handle_endtag(self, tag: str) -> None:
+ tag = tag.casefold()
+ if tag == "a":
+ if self.links and self.links.pop():
+ self.parts.append("")
+ return
+ if tag in self._TAGS and tag != "br":
+ self.parts.append(f"{tag}>")
+
+ def handle_data(self, data: str) -> None:
+ self.parts.append(str(escape(data)))
+
+
+def service_html(value: str) -> Markup:
+ sanitizer = _ServiceHtmlSanitizer()
+ sanitizer.feed(value or "")
+ sanitizer.close()
+ return Markup("".join(sanitizer.parts))
+
+
+def _service_index() -> tuple[dict[str, str], ...]:
+ """Return every captured service once, preserving modelled destinations."""
+ rows: list[dict[str, str]] = [dict(row) for row in MODELLED_SERVICES]
+ seen = {row["label"].casefold() for row in rows}
+ for group in SERVICE_GROUPS:
+ for service in group["services"]:
+ label = str(service["label"])
+ if label.casefold() in seen:
+ continue
+ rows.append({"label": label, "href": str(service["href"])})
+ seen.add(label.casefold())
+ return tuple(rows)
+
+
+SERVICE_INDEX = _service_index()
+HOME_TASK_FAMILIES = task_catalog.FAMILIES
+HOME_POPULAR_PROJECTS = task_catalog.POPULAR_PROJECTS
+HOME_TASKS = task_catalog.TASKS
+HOME_FAMILY_BY_ID = {
+ str(family["id"]): family for family in HOME_TASK_FAMILIES
+}
+
+# The authenticated landing surface is a different source page from the
+# public marketing homepage. Keep its source-observed ordering and copy
+# explicit: this is the compact task launcher visible before "See More", not
+# another rendering of the public category-family catalog.
+TASKBOOK_QUICK_TASKS: tuple[dict[str, str], ...] = (
+ {
+ "label": "IKEA Furniture Assembly",
+ "href": "/book/task/ikea-assembly",
+ },
+ {"label": "Moving", "href": "/dashboard/category/moving"},
+ {
+ "label": "Truck Assisted Help Moving",
+ "href": "/book/task/truck-assisted-help-moving",
+ },
+ {
+ "label": "Furniture Assembly",
+ "href": "/book/furniture-assembly/furniture-assembly",
+ },
+ {"label": "General Mounting", "href": "/book/task/other-mounting"},
+ {"label": "Cleaning", "href": "/book/task/cleaning"},
+ {"label": "TV Mounting", "href": "/book/task/tv-mounting"},
+)
+
+TASKBOOK_MORE_TASKS: tuple[dict[str, str], ...] = (
+ {"label": "Help Moving", "href": "/book/help-moving"},
+ {"label": "Home Repairs", "href": "/dashboard/category/home-repairs"},
+ {"label": "Yardwork", "href": "/dashboard/category/outdoor-help"},
+ {"label": "Painting", "href": "/dashboard/category/painting"},
+ {"label": "Electrical Help", "href": "/book/task/electrical-help"},
+ {"label": "Plumbing Help", "href": "/book/task/plumbing-help"},
+)
+
+TASKBOOK_RECOMMENDATIONS: tuple[dict[str, object], ...] = (
+ {
+ "slug": "alfonso-m",
+ "name": "Alfonso M.",
+ "image": (
+ "/static/furniture-p1-assets/"
+ "qvxdo2jfnbwmqw2o6xry-a38a2b72df73.webp"
+ ),
+ "completed_tasks": "1,272",
+ "rating": "5.0",
+ "reviews": "598",
+ "top_skill": "Plumbing help",
+ "rate": "$91.80/hr",
+ "href": "/book/task/plumbing-help",
+ },
+ {
+ "slug": "casual-v",
+ "name": "Casual V.",
+ "image": (
+ "/static/assets/source-current/"
+ "2026-08-08-furniture-booking-auth/"
+ "eeel7pkeasiqe2q38pdk-10349f1f22.jpg"
+ ),
+ "completed_tasks": "867",
+ "rating": "5.0",
+ "reviews": "484",
+ "top_skill": "Furniture Assembly",
+ "rate": "$62.14/hr",
+ "href": "/book/furniture-assembly/furniture-assembly",
+ },
+)
+TASKBOOK_RECOMMENDATION_BY_SLUG: dict[str, dict[str, object]] = {
+ str(tasker["slug"]): tasker for tasker in TASKBOOK_RECOMMENDATIONS
+}
+
+
+def booking_href_for_category(category_id: str) -> str:
+ """Return the local booking entry for a server-owned category."""
+ configured = task_catalog.BOOKING_HREFS.get(category_id)
+ if configured:
+ return configured
+ service_configured = service_booking_catalog.BOOKING_HREFS.get(category_id)
+ if service_configured:
+ return service_configured
+ if category_id == CATEGORY_ID:
+ return "/book/help-moving"
+ return f"/book/furniture-assembly/{quote(category_id)}"
+
+
+def furniture_card_by_slug(
+ slug: str, *, detail: bool = False
+) -> dict[str, Any] | None:
+ key = "detail_slug" if detail else "slug"
+ return next(
+ (card for card in FURNITURE_CARDS if card[key] == slug),
+ None,
+ )
+
+# Seed-data conveniences (ordinary rows, surfaced for templates/tests).
+CATEGORY_ID = db.CATEGORY_ID
+CATEGORY_LABEL = db.CATEGORY_LABEL
+APARTMENT_SIZE = db.APARTMENT_SIZE
+APARTMENT_LABEL = db.APARTMENT_LABEL
+FIXTURE_ADDRESS_ID = db.FIXTURE_ADDRESS_ID
+FIXTURE_ADDRESS = db.FIXTURE_ADDRESS
+
+BOOKING_ID = db.BOOKING_ID
+REQUEST_ID = db.REQUEST_ID
+FOREIGN_BOOKING_ID = db.FOREIGN_BOOKING_ID
+FOREIGN_REQUEST_ID = db.FOREIGN_REQUEST_ID
+SLOT_VERSION = db.SLOT_VERSION
+WINDOW_START = db.WINDOW_START
+WINDOW_END = db.WINDOW_END
+
+SESSION_COOKIE = str(SESSION_COOKIE_CONFIG["name"])
+SESSION_ACCOUNT = db.SESSION_ACCOUNT
+FOREIGN_ACCOUNT = db.FOREIGN_ACCOUNT
+TASKER_ACCOUNT = db.TASKER_ACCOUNT
+CSRF_VALUE = "taskrabbit-local-form-2026-07-29"
+
+SEED_AUTH_ACCOUNTS = {
+ SESSION_ACCOUNT: {
+ "email": "morgan@example.test",
+ "display_name": "Morgan Lee",
+ "password": os.environ.get(
+ "WEBSITEBENCH_EVALUATOR_PRIMARY_SECRET", "Taskrabbit-Morgan-2026!"
+ ),
+ },
+ FOREIGN_ACCOUNT: {
+ "email": "robin@example.test",
+ "display_name": "Robin Lee",
+ "password": os.environ.get(
+ "WEBSITEBENCH_EVALUATOR_SECONDARY_SECRET", "Taskrabbit-Robin-2026!"
+ ),
+ },
+ TASKER_ACCOUNT: {
+ "email": "taylor.tasker@example.test",
+ "display_name": "Taylor Tasker",
+ "password": "Taskrabbit-Taylor-2026!",
+ },
+}
+
+DEFAULT_TASKER_ID = db.DEFAULT_TASKER_ID
+TASKER_LABEL = "Tasker"
+
+ADMIN_TOKEN_HEADER = "X-WebsiteBench-Admin-Token"
+
+# 'Next Saturday' is derived arithmetically from the frozen clock.
+NEXT_SATURDAY = db.next_saturday(FROZEN_NOW)
+NEXT_SATURDAY_ISO = NEXT_SATURDAY.strftime("%Y-%m-%d")
+assert NEXT_SATURDAY_ISO == db.BOOKING_DATE
+
+
+def date_label(iso_date: str) -> str:
+ """'2026-08-01' -> 'Saturday, August 1, 2026' (locale-independent)."""
+ moment = datetime.strptime(iso_date, "%Y-%m-%d")
+ return (
+ f"{moment.strftime('%A')}, {moment.strftime('%B')} "
+ f"{moment.day}, {moment.year}"
+ )
+
+
+def relative_date_phrase(iso_date: str) -> str | None:
+ """Human phrase computed from the frozen clock by date arithmetic."""
+ if iso_date == NEXT_SATURDAY_ISO:
+ return "Next Saturday"
+ return None
+
+
+NEXT_SATURDAY_LABEL = date_label(NEXT_SATURDAY_ISO)
+
+ROOT = _CLONE_DIR
+_PHONE_REGION_CATALOG = json.loads(
+ (ROOT / "frontend" / "phone_regions.json").read_text(encoding="utf-8")
+)
+if (
+ _PHONE_REGION_CATALOG.get("schema_version")
+ != "websitebench.taskrabbit.phone-regions.v1"
+):
+ raise RuntimeError("Taskrabbit phone-region catalog has an unsupported schema")
+PHONE_REGIONS = tuple(_PHONE_REGION_CATALOG.get("regions", ()))
+PHONE_REGIONS_BY_CODE = {
+ str(region.get("code", "")): region for region in PHONE_REGIONS
+}
+if (
+ len(PHONE_REGIONS) < 200
+ or len(PHONE_REGIONS_BY_CODE) != len(PHONE_REGIONS)
+ or "US" not in PHONE_REGIONS_BY_CODE
+ or any(
+ not re.fullmatch(r"[A-Z]{2}", str(region.get("code", "")))
+ or not re.fullmatch(r"\+[1-9]\d{0,3}", str(region.get("dial_code", "")))
+ or not str(region.get("name", "")).strip()
+ or not str(region.get("symbol", "")).strip()
+ for region in PHONE_REGIONS
+ )
+):
+ raise RuntimeError("Taskrabbit phone-region catalog is incomplete or invalid")
+templates = Jinja2Templates(directory=str(ROOT / "frontend" / "templates"))
+templates.env.globals["public_registration_enabled"] = (
+ PUBLIC_REGISTRATION_VERIFICATION is not None
+)
+templates.env.globals["phone_regions"] = PHONE_REGIONS
+templates.env.globals["phone_regions_by_code"] = PHONE_REGIONS_BY_CODE
+templates.env.globals["service_cta_href"] = service_cta_href
+templates.env.globals["service_booking_href"] = service_booking_href
+templates.env.globals["service_html"] = service_html
+
+# Persistent database: SiteBackend performed the binding preflight before any
+# site migration or seed write.
+DB_FILE = SITE_BACKEND.lifecycle.database_path
+AUTH_STORE = LocalAuthStore(
+ DB_FILE,
+ site_id=SITE_ID,
+ now=lambda: int(FROZEN_NOW.timestamp()),
+)
+AUTH_STORE.ensure_schema()
+for _subject_id, _credentials in SEED_AUTH_ACCOUNTS.items():
+ AUTH_STORE.seed_account(
+ subject_id=_subject_id,
+ email=_credentials["email"],
+ display_name=_credentials["display_name"],
+ password=_credentials["password"],
+ )
+AUTH_STORE.reconcile_mail()
+with db.session(DB_FILE) as _seed_connection:
+ SEED_AUTH_ACCOUNT_COLUMNS = tuple(
+ str(row["name"])
+ for row in _seed_connection.execute(
+ "PRAGMA table_info(local_auth_accounts)"
+ ).fetchall()
+ )
+ SEED_AUTH_ACCOUNT_ROWS = tuple(
+ tuple(row[column] for column in SEED_AUTH_ACCOUNT_COLUMNS)
+ for row in _seed_connection.execute(
+ "SELECT * FROM local_auth_accounts WHERE subject_id IN (?,?,?) "
+ "ORDER BY subject_id",
+ tuple(SEED_AUTH_ACCOUNTS),
+ ).fetchall()
+ )
+
+
+def db_session(*, immediate: bool = False) -> Any:
+ return db.session(DB_FILE, immediate=immediate)
+
+
+def public_tasker(tasker: dict[str, Any]) -> dict[str, Any]:
+ """Return source-like presentation fields without changing stored identity."""
+ item = dict(tasker)
+ item["name"] = re.sub(r"\s*\(Simulated\)\s*$", "", str(item["name"]))
+ if str(item.get("blurb", "")).startswith("Fixture profile:"):
+ item["blurb"] = str(item["blurb"]).removeprefix("Fixture profile:").strip()
+ return item
+
+
+def public_address(address: dict[str, Any]) -> dict[str, Any]:
+ """Expose a stable opaque form value without leaking seed identifiers."""
+ item = dict(address)
+ item["public_id"] = "address-" + hashlib.sha256(
+ str(item["id"]).encode("utf-8")
+ ).hexdigest()[:16]
+ return item
+
+
+def owned_address_from_public_id(
+ conn: Any, owner: str, public_id: str
+) -> dict[str, Any] | None:
+ for address in db.list_addresses(conn, owner):
+ if public_address(address)["public_id"] == public_id:
+ return address
+ # Compatibility adapter for previously generated local test clients. The
+ # raw seed ID is never emitted into public HTML.
+ return db.get_owned_address(conn, owner, public_id)
+
+
+def load_taskers() -> list[dict[str, Any]]:
+ with db_session() as conn:
+ return [public_tasker(tasker) for tasker in db.list_taskers(conn)]
+
+
+class BookingsView:
+ """Live, dict-like view of the seed client's persisted bookings.
+
+ Kept for the test surface (``app_module.BOOKINGS``); every read goes
+ straight to the SQLite database, so the view always reflects durable
+ state. The seeded foreign-owned booking is excluded: it belongs to a
+ different account.
+ """
+
+ def _snapshot(self) -> dict[str, dict[str, Any]]:
+ with db_session() as conn:
+ rows = db.list_bookings(conn, owner=SESSION_ACCOUNT)
+ return {row["id"]: row for row in rows}
+
+ def __eq__(self, other: object) -> bool:
+ return self._snapshot() == other
+
+ def __len__(self) -> int:
+ return len(self._snapshot())
+
+ def __contains__(self, key: object) -> bool:
+ return key in self._snapshot()
+
+ def __getitem__(self, key: str) -> dict[str, Any]:
+ return self._snapshot()[key]
+
+ def get(self, key: str, default: Any = None) -> Any:
+ return self._snapshot().get(key, default)
+
+ def keys(self) -> Any:
+ return self._snapshot().keys()
+
+ def __iter__(self) -> Iterator[str]:
+ return iter(self._snapshot())
+
+ def __repr__(self) -> str: # pragma: no cover - debug aid
+ return f"BookingsView({self._snapshot()!r})"
+
+
+BOOKINGS = BookingsView()
+
+app = FastAPI(
+ title="TaskRabbit R3 persistent backend",
+ docs_url=None,
+ redoc_url=None,
+ openapi_url=None,
+)
+
+
+@app.get("/static/auth-verification.js", include_in_schema=False)
+async def public_registration_verification_script():
+ return registration_script_response(PUBLIC_REGISTRATION_VERIFICATION)
+
+
+app.mount("/static", StaticFiles(directory=str(ROOT / "static")), name="static")
+admin_app = FastAPI(
+ title="TaskRabbit verifier control plane",
+ docs_url=None,
+ redoc_url=None,
+ openapi_url=None,
+)
+
+
+@app.middleware("http")
+async def runtime_headers(request: Request, call_next):
+ original_token = request.cookies.get(SESSION_COOKIE)
+ auth_token, auth_session = AUTH_STORE.ensure_session(original_token)
+ request.state.auth_token = auth_token
+ request.state.auth_session = auth_session
+ response = await call_next(request)
+ final_token = request.state.auth_token
+ if final_token != original_token:
+ response.set_cookie(
+ SESSION_COOKIE,
+ final_token,
+ httponly=bool(SESSION_COOKIE_CONFIG["httponly"]),
+ samesite=str(SESSION_COOKIE_CONFIG["samesite"]),
+ secure=bool(SESSION_COOKIE_CONFIG["secure"]),
+ path=str(SESSION_COOKIE_CONFIG["path"]),
+ max_age=30 * 24 * 60 * 60,
+ )
+ response.headers["Content-Security-Policy"] = (
+ "default-src 'self'; img-src 'self' data:; style-src 'self'; "
+ "script-src 'self'; connect-src 'self'; font-src 'self'; "
+ "object-src 'none'; frame-ancestors 'none'; base-uri 'self'; "
+ "form-action 'self'"
+ )
+ response.headers["Referrer-Policy"] = "no-referrer"
+ response.headers["X-Content-Type-Options"] = "nosniff"
+ return response
+
+
+def current_account(request: Request) -> str | None:
+ auth_session = getattr(request.state, "auth_session", None)
+ if not isinstance(auth_session, dict):
+ return None
+ account = auth_session.get("account")
+ if not isinstance(account, dict):
+ return None
+ subject_id = account.get("subject_id")
+ return str(subject_id) if isinstance(subject_id, str) else None
+
+
+def current_account_email(request: Request) -> str:
+ auth_session = getattr(request.state, "auth_session", None)
+ account = auth_session.get("account") if isinstance(auth_session, dict) else None
+ if not isinstance(account, dict):
+ return ""
+ return str(account.get("email_normalized") or account.get("email") or "")
+
+
+def current_principal(request: Request) -> dict[str, Any] | None:
+ """Resolve the authenticated subject's site role from server-owned data."""
+ subject_id = current_account(request)
+ if subject_id is None:
+ return None
+ with db_session() as conn:
+ return db.get_client(conn, subject_id)
+
+
+def signed_in(request: Request) -> bool:
+ return current_account(request) is not None
+
+
+def owner_draft(request: Request) -> dict[str, Any]:
+ account = current_account(request)
+ if account is None:
+ return {}
+ with db_session() as conn:
+ return db.get_draft(conn, account) or {}
+
+
+def owner_request_id(request: Request) -> str:
+ """The signed-in client's pre-confirm request ID (seed ID otherwise)."""
+ draft = owner_draft(request)
+ if draft.get("booking_ref"):
+ return str(draft["booking_ref"])
+ return db.SEED_DRAFT_REF
+
+
+def first_open_slot() -> dict[str, Any]:
+ with db_session() as conn:
+ slots = db.list_open_slots(conn)
+ if slots:
+ return slots[0]
+ # Degenerate fallback (empty catalog): derive next Saturday morning.
+ return {
+ "id": "",
+ "version": "",
+ "date": NEXT_SATURDAY_ISO,
+ "window_start": "09:00",
+ "window_end": "13:00",
+ }
+
+
+def session_binding(request: Request) -> str:
+ token = str(getattr(request.state, "auth_token", ""))
+ return "sha256:" + hashlib.sha256(token.encode("utf-8")).hexdigest()
+
+
+def page_context(request: Request, **values: object) -> dict[str, object]:
+ slot = first_open_slot()
+ account = current_account(request)
+ auth_session = getattr(request.state, "auth_session", {})
+ auth_account = (
+ auth_session.get("account")
+ if isinstance(auth_session, dict)
+ else None
+ )
+ with db_session() as conn:
+ taskers = [public_tasker(tasker) for tasker in db.list_taskers(conn)]
+ sizes = [
+ dict(row)
+ for row in conn.execute(
+ "SELECT * FROM apartment_sizes ORDER BY rowid"
+ ).fetchall()
+ ]
+ open_slots = db.list_open_slots(conn)
+ addresses = (
+ [public_address(address) for address in db.list_addresses(conn, account)]
+ if account
+ else []
+ )
+ display_address = addresses[0] if addresses else None
+ draft = db.get_draft(conn, account) if account else None
+ draft_category_id = str((draft or {}).get("category") or CATEGORY_ID)
+ draft_category = db.get_category(conn, draft_category_id)
+ wizard_category_label = (
+ str(draft_category["label"])
+ if draft_category is not None
+ else CATEGORY_LABEL
+ )
+ wizard_start_href = booking_href_for_category(draft_category_id)
+ context: dict[str, object] = {
+ "request": request,
+ "site_id": SITE_ID,
+ "stage": STAGE,
+ "version": VERSION,
+ "frozen_clock": FROZEN_CLOCK,
+ "assets_base": ASSETS_BASE,
+ "signed_in": account is not None,
+ "current_path": request.url.path,
+ "category_id": CATEGORY_ID,
+ "category_label": CATEGORY_LABEL,
+ "wizard_category_label": wizard_category_label,
+ "wizard_start_href": wizard_start_href,
+ "apartment_size": APARTMENT_SIZE,
+ "apartment_label": APARTMENT_LABEL,
+ "apartment_sizes": sizes,
+ "fixture_address_id": public_address(
+ {"id": FIXTURE_ADDRESS_ID}
+ )["public_id"],
+ "fixture_address": (
+ db.address_label(display_address)
+ if display_address
+ else FIXTURE_ADDRESS
+ ),
+ "request_id": owner_request_id(request),
+ "slot_version": slot["version"],
+ "window_start": slot["window_start"],
+ "window_end": slot["window_end"],
+ "next_saturday_iso": slot["date"],
+ "next_saturday_label": date_label(slot["date"]),
+ "relative_phrase": relative_date_phrase(slot["date"]),
+ "open_slots": open_slots,
+ "taskers": taskers,
+ "tasker_label": TASKER_LABEL,
+ "csrf": CSRF_VALUE,
+ "client_name": (
+ str(auth_account.get("display_name"))
+ if isinstance(auth_account, dict)
+ else ""
+ ),
+ }
+ context.update(values)
+ return context
+
+
+def render(
+ request: Request,
+ template: str,
+ *,
+ status_code: int = 200,
+ **values: object,
+) -> HTMLResponse:
+ internal_state = str(values.get("state", "loaded"))
+ values["public_state"] = {
+ "fixture-address-offered": "saved-addresses",
+ "simulated-taskers": "tasker-options",
+ "simulation-disclosure": "booking-details",
+ "synthetic-identity-disclosure": "account-details",
+ }.get(internal_state, internal_state)
+ return templates.TemplateResponse(
+ request=request,
+ name=template,
+ context=page_context(request, **values),
+ status_code=status_code,
+ )
+
+
+async def urlencoded_form(request: Request) -> dict[str, list[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")
+ return parse_qs(raw, keep_blank_values=True, strict_parsing=False)
+
+
+def single(values: dict[str, list[str]], key: str) -> str:
+ items = values.get(key, [])
+ return items[-1] if items else ""
+
+
+def safe_next(value: str | None, request: Request | None = None) -> str:
+ if value and value.startswith("/") and not value.startswith("//"):
+ # The source does not expose its public marketing homepage once an
+ # account is authenticated. Login forms historically posted `/` as
+ # their next path, so canonicalize that legacy value to Task Book.
+ return "/dashboard" if value == "/" else value
+ return "/dashboard"
+
+
+def normalize_state(state: str, allowed: set[str], default: str) -> str:
+ return state if state in allowed else default
+
+
+# The captured source registration form carries first name, last name, phone
+# number, postal code and a terms checkbox alongside email and password. The
+# local account model persists only a display name, an email and a password —
+# so the rest are validated here rather than merely rendered. A field that
+# cannot affect the outcome is decoration, and decoration on an auth form is
+# the kind of quiet lie this project exists to avoid.
+US_POSTAL_CODE = re.compile(r"^\d{5}(?:-\d{4})?$")
+PHONE_DIGITS = re.compile(r"\d")
+
+
+def registration_profile_errors(values: Mapping[str, list[str]]) -> list[str]:
+ """Validate the captured profile fields. Returns human-readable errors."""
+
+ errors: list[str] = []
+ given = (single(values, "givenName") or "").strip()
+ family = (single(values, "familyName") or "").strip()
+ phone = (single(values, "phone") or "").strip()
+ phone_region = (single(values, "phoneRegion") or "US").strip().upper()
+ postal = (single(values, "postalCode") or "").strip()
+ accepted = (single(values, "acceptTerms") or "").strip()
+
+ if not given:
+ errors.append("Enter your first name.")
+ if not family:
+ errors.append("Enter your last name.")
+ # US baseline is frozen in clone.yaml (locale en-US, delivery_region US),
+ # so the postal code is validated as a US ZIP and nothing else.
+ if not US_POSTAL_CODE.match(postal):
+ errors.append("Enter a valid US postal code, for example 94103.")
+ phone_digit_count = len(PHONE_DIGITS.findall(phone))
+ selected_region = PHONE_REGIONS_BY_CODE.get(
+ phone_region, PHONE_REGIONS_BY_CODE["US"]
+ )
+ minimum_phone_digits = (
+ 10 if selected_region["dial_code"] == "+1" else 7
+ )
+ if phone_digit_count < minimum_phone_digits or phone_digit_count > 15:
+ errors.append("Enter a phone number including area code.")
+ if phone_region not in PHONE_REGIONS_BY_CODE:
+ errors.append("Select a valid phone country or region.")
+ if not accepted:
+ errors.append(
+ "Agree to the Terms of Service and Privacy Policy to continue."
+ )
+ return errors
+
+
+def registration_display_name(values: Mapping[str, list[str]]) -> str:
+ """Compose the stored display name from the source's two name fields."""
+
+ parts = [
+ (single(values, "givenName") or "").strip(),
+ (single(values, "familyName") or "").strip(),
+ ]
+ composed = " ".join(part for part in parts if part)
+ return composed or (single(values, "display_name") or "")
+
+
+def registration_form_values(values: Mapping[str, list[str]]) -> dict[str, str]:
+ """Re-render the form with what the visitor already typed, minus secrets."""
+
+ phone_region = (single(values, "phoneRegion") or "US").strip().upper()
+ region = PHONE_REGIONS_BY_CODE.get(
+ phone_region, PHONE_REGIONS_BY_CODE["US"]
+ )
+ return {
+ "form_email": single(values, "email") or "",
+ "form_given_name": single(values, "givenName") or "",
+ "form_family_name": single(values, "familyName") or "",
+ "form_phone": single(values, "phone") or "",
+ "form_phone_region": str(region["code"]),
+ # Derive the calling code from the selected region. This keeps the
+ # no-script POST path correct and prevents a stale or edited hidden
+ # field from changing the re-rendered selection.
+ "form_phone_country": str(region["dial_code"]),
+ "form_postal_code": single(values, "postalCode") or "",
+ "form_accept_terms": bool(single(values, "acceptTerms")),
+ }
+
+
+def unauthorized_boundary(request: Request, next_path: str) -> HTMLResponse:
+ return render(
+ request,
+ "login.html",
+ page_title="Sign up or log in",
+ state="unauthorized",
+ next_path=next_path,
+ unauthorized=True,
+ status_code=401,
+ )
+
+
+def role_forbidden_page(request: Request) -> HTMLResponse:
+ return render(
+ request,
+ "error.html",
+ page_title="Access refused",
+ state="role-forbidden",
+ message="This account cannot create or manage booking requests.",
+ status_code=403,
+ )
+
+
+def csrf_forbidden_page(request: Request) -> HTMLResponse:
+ return render(
+ request,
+ "error.html",
+ page_title="Form expired",
+ state="form-expired",
+ message="This form expired. Reload the page and try again.",
+ status_code=403,
+ )
+
+
+def booking_requester(
+ request: Request, next_path: str
+) -> tuple[str | None, HTMLResponse | None]:
+ """Return the server-resolved requester or a product boundary response."""
+ account = current_account(request)
+ if account is None:
+ return None, unauthorized_boundary(request, next_path)
+ principal = current_principal(request)
+ if principal is None or principal.get("role") != "requester":
+ return None, role_forbidden_page(request)
+ return account, None
+
+
+def save_draft(request: Request, **fields: str) -> None:
+ """Persist wizard progress as the owner's draft booking (with version)."""
+ account = current_account(request)
+ if account is None:
+ return
+ with db_session() as conn:
+ before = db.get_draft(conn, account) or {}
+ db.update_draft(conn, account, **fields)
+ payment_binding_fields = {"category", "slot_id", "tasker_id"}
+ if any(
+ key in payment_binding_fields
+ and str(before.get(key) or "") != str(value or "")
+ for key, value in fields.items()
+ ):
+ db.clear_draft_payment(conn, account)
+
+
+def open_slot_summary() -> str:
+ with db_session() as conn:
+ slots = db.list_open_slots(conn)
+ return "; ".join(
+ f"{slot['date']} {slot['window_start']}-{slot['window_end']}"
+ for slot in slots
+ )
+
+
+@app.get("/healthz")
+async def healthz() -> JSONResponse:
+ return JSONResponse(
+ {"status": "ok"},
+ headers={
+ "X-WebsiteBench-Container-Build-ID": os.environ.get(
+ "DEPLOYMENT_BUILD_ID", os.environ.get("SOURCE_REF", "")
+ )
+ },
+ )
+
+
+def admin_authorized(request: Request) -> bool:
+ expected = db.admin_token()
+ supplied = request.headers.get(ADMIN_TOKEN_HEADER, "")
+ return (
+ expected is not None
+ and bool(supplied)
+ and hmac.compare_digest(supplied, expected)
+ )
+
+
+@admin_app.get("/__admin/healthz")
+async def admin_healthz(request: Request) -> JSONResponse:
+ if not admin_authorized(request):
+ return JSONResponse(
+ {"status": "not-found" if db.admin_token() is None else "unauthorized"},
+ status_code=404 if db.admin_token() is None else 401,
+ )
+ with db_session() as conn:
+ head = db.migration_head(conn)
+ return JSONResponse(
+ {
+ "status": "ok",
+ "ok": True,
+ "site_id": SITE_ID,
+ "stage": STAGE,
+ "version": VERSION,
+ "candidate_id": CANDIDATE_ID,
+ "frozen_clock": FROZEN_CLOCK,
+ "persistent_backend": True,
+ "db": {
+ "path": str(DB_FILE),
+ "migration_head": head,
+ "auth_migrations": AUTH_STORE.applied_migrations(),
+ },
+ }
+ )
+
+
+@admin_app.post("/__admin/reset")
+async def admin_reset(request: Request) -> JSONResponse:
+ if not admin_authorized(request):
+ return JSONResponse(
+ {
+ "ok": False,
+ "error": (
+ "not found"
+ if db.admin_token() is None
+ else "invalid or missing admin token"
+ ),
+ },
+ status_code=404 if db.admin_token() is None else 401,
+ )
+ with db_session(immediate=True) as conn:
+ details = db.reset_state(conn)
+ # Restore the byte-exact seed credential rows captured at startup.
+ # Re-hashing on every reset would create random salts, make identical
+ # baselines hash differently, and needlessly slow 189 isolated
+ # mutation tuples.
+ conn.execute("DELETE FROM local_auth_accounts")
+ placeholders = ",".join("?" for _ in SEED_AUTH_ACCOUNT_COLUMNS)
+ columns = ",".join(
+ f'"{column}"' for column in SEED_AUTH_ACCOUNT_COLUMNS
+ )
+ conn.executemany(
+ f"INSERT INTO local_auth_accounts ({columns}) "
+ f"VALUES ({placeholders})",
+ SEED_AUTH_ACCOUNT_ROWS,
+ )
+ head = db.migration_head(conn)
+ return JSONResponse(
+ {
+ "ok": True,
+ "site_id": SITE_ID,
+ "reset": details,
+ "db": {"path": str(DB_FILE), "migration_head": head},
+ }
+ )
+
+
+@app.get("/", response_class=HTMLResponse)
+async def home(
+ request: Request,
+ state: str = "loaded",
+ category: str = "assembly",
+) -> HTMLResponse:
+ if signed_in(request):
+ return RedirectResponse("/dashboard", status_code=303)
+ normalized = normalize_state(
+ state,
+ {
+ "loaded",
+ "category-nav",
+ "popular-projects",
+ "promotion-modal",
+ "promotion-dismissed",
+ "promotion-submission-acknowledgment",
+ "loading",
+ "error",
+ },
+ "loaded",
+ )
+ selected_family = HOME_FAMILY_BY_ID.get(category) or HOME_TASK_FAMILIES[0]
+ return render(
+ request,
+ "home.html",
+ page_title="Book trusted help for home tasks",
+ state=normalized,
+ home_task_families=HOME_TASK_FAMILIES,
+ active_home_family=selected_family,
+ popular_projects=HOME_POPULAR_PROJECTS,
+ )
+
+
+def search_services(query: str) -> list[dict[str, str]]:
+ """Match the service index by substring, modelled routes first.
+
+ Ranking is deliberately simple and total: a prefix match beats a substring
+ match, and a service the clone models end to end beats one that only has an
+ honest destination, so a search for "moving" offers the bookable page
+ before the placeholders.
+ """
+ needle = " ".join(query.lower().split())
+ if not needle:
+ return []
+ scored: list[tuple[int, int, str, dict[str, str]]] = []
+ for entry in SERVICE_INDEX:
+ label = entry["label"].lower()
+ if needle not in label:
+ continue
+ starts = 0 if label.startswith(needle) else 1
+ modelled = 0 if not entry["href"].startswith("/out/") else 1
+ scored.append((modelled, starts, label, entry))
+ scored.sort(key=lambda row: (row[0], row[1], row[2]))
+ return [entry for _, _, _, entry in scored]
+
+
+@app.get("/services", response_class=HTMLResponse)
+async def services_index(
+ request: Request, state: str = "loaded", q: str | None = None
+) -> HTMLResponse:
+ normalized = normalize_state(
+ state, {"loaded", "category-grid", "loading", "empty", "error"}, "loaded"
+ )
+ query = (q or "").strip()
+ # The home search band posts here with GET. Honouring `q` on the server is
+ # what makes that form work with scripting unavailable; the suggestion
+ # endpoint below is only an enhancement on top of this.
+ results = search_services(query) if query else []
+ if query and not results:
+ normalized = "empty"
+ return render(
+ request,
+ "services.html",
+ page_title="All services",
+ state=normalized,
+ search_query=query,
+ search_results=results,
+ services_hero=_SERVICES_CATALOG_VALUE["hero"],
+ service_groups=SERVICE_GROUPS,
+ )
+
+
+@app.get("/api/services/suggest", include_in_schema=False)
+async def services_suggest(q: str | None = None) -> JSONResponse:
+ """Type-ahead source for the search band. Read-only, no session effect."""
+ query = (q or "").strip()
+ results = search_services(query)[:8]
+ return JSONResponse(
+ {"query": query, "results": results},
+ headers={"Cache-Control": "no-store"},
+ )
+
+
+@app.get("/services/furniture-assembly", response_class=HTMLResponse)
+async def furniture_assembly_landing(
+ request: Request,
+ state: str = "loaded",
+) -> HTMLResponse:
+ """Render the captured Furniture Assembly service catalog."""
+ normalized = normalize_state(
+ state,
+ {"loaded", "help-dialog-open"},
+ "loaded",
+ )
+ return render(
+ request,
+ "furniture.html",
+ page_title="Furniture Assembly & Installation Services",
+ state=normalized,
+ furniture_cards=FURNITURE_CARDS,
+ furniture_steps=FURNITURE_STEPS,
+ furniture_reviews=FURNITURE_REVIEWS,
+ furniture_faqs=FURNITURE_FAQS,
+ furniture_other_tasks=FURNITURE_OTHER_TASKS,
+ header_variant="furniture-header",
+ )
+
+
+@app.get(
+ "/services/furniture-assembly/{detail_slug}",
+ response_class=HTMLResponse,
+)
+async def furniture_service_detail(
+ request: Request, detail_slug: str
+) -> HTMLResponse:
+ card = furniture_card_by_slug(detail_slug, detail=True)
+ detail = FURNITURE_DETAIL_CONTENT.get(detail_slug)
+ if card is None or detail is None:
+ return not_found_page(
+ request, "We couldn't find that furniture assembly service."
+ )
+ source_path = f"/services/furniture-assembly/{detail_slug}"
+ source_page = SERVICE_PAGES_BY_PATH[source_path]
+ return render(
+ request,
+ "furniture_detail.html",
+ page_title=f"{card['title']} Services",
+ meta_description=str(source_page["meta_description"]),
+ canonical_path=source_path,
+ state="loaded",
+ furniture_card=card,
+ furniture_detail=detail,
+ furniture_source_page=source_page,
+ furniture_detail_assets_base=FURNITURE_DETAIL_ASSETS_BASE,
+ furniture_detail_steps=FURNITURE_DETAIL_STEPS,
+ furniture_detail_cities=FURNITURE_DETAIL_CITIES,
+ header_variant="furniture-header",
+ )
+
+
+@app.get("/near-me/assemble-furniture", response_class=HTMLResponse)
+async def furniture_near_me(request: Request) -> HTMLResponse:
+ card = furniture_card_by_slug("assemble-furniture", detail=True)
+ assert card is not None
+ detail = dict(FURNITURE_DETAIL_CONTENT["assemble-furniture"])
+ detail["hero_title"] = "Furniture Assembly Near You"
+ return render(
+ request,
+ "furniture_detail.html",
+ page_title="Furniture Assembly Near You",
+ state="loaded",
+ furniture_card=card,
+ furniture_detail=detail,
+ furniture_detail_assets_base=FURNITURE_DETAIL_ASSETS_BASE,
+ furniture_detail_steps=FURNITURE_DETAIL_STEPS,
+ furniture_detail_cities=FURNITURE_DETAIL_CITIES,
+ detail_heading="Furniture Assembly Near You",
+ header_variant="furniture-header",
+ )
+
+
+@app.get("/book/furniture-assembly/{service_slug}", response_class=HTMLResponse)
+async def furniture_booking_form(
+ request: Request,
+ service_slug: str,
+ state: str = "ready",
+) -> HTMLResponse:
+ card = furniture_card_by_slug(service_slug)
+ if card is None:
+ return not_found_page(
+ request, "We couldn't find that furniture assembly service."
+ )
+ path = f"/book/furniture-assembly/{service_slug}"
+ _account, boundary = booking_requester(request, path)
+ if boundary is not None:
+ return boundary
+ normalized = normalize_state(
+ state,
+ {
+ "ready",
+ "apartment-size-selected",
+ "validation",
+ "loading",
+ "error",
+ },
+ "ready",
+ )
+ errors = (
+ ["Select a valid task size to continue."]
+ if normalized == "validation"
+ else []
+ )
+ draft = owner_draft(request)
+ selected_size = (
+ str(draft.get("apartment_size") or APARTMENT_SIZE)
+ if str(draft.get("category")) == service_slug
+ else APARTMENT_SIZE
+ )
+ return render(
+ request,
+ "book_form.html",
+ page_title=f"Book {card['title']}",
+ state=normalized,
+ errors=errors,
+ form_category=service_slug,
+ form_size=selected_size,
+ booking_form_action=path,
+ booking_reload_href=path,
+ booking_heading=f"{card['title']} — describe your task",
+ booking_intro=(
+ "Tell us about your task so we can show matching Taskers."
+ ),
+ booking_size_legend="Task size",
+ wizard_category_label=str(card["title"]),
+ wizard_start_href=path,
+ )
+
+
+@app.post("/book/furniture-assembly/{service_slug}")
+async def furniture_booking_form_submit(
+ request: Request, service_slug: str
+):
+ card = furniture_card_by_slug(service_slug)
+ if card is None:
+ return not_found_page(
+ request, "We couldn't find that furniture assembly service."
+ )
+ path = f"/book/furniture-assembly/{service_slug}"
+ account, boundary = booking_requester(request, path)
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ size = single(values, "apartment_size")
+ with db_session() as conn:
+ valid_size = db.get_size(conn, size)
+ valid_category = db.get_category(conn, service_slug)
+ if valid_size is None or valid_category is None:
+ return render(
+ request,
+ "book_form.html",
+ page_title=f"Book {card['title']}",
+ state="validation",
+ errors=["Select a valid task size to continue."],
+ form_category=service_slug,
+ form_size=size,
+ booking_form_action=path,
+ booking_reload_href=path,
+ booking_heading=f"{card['title']} — describe your task",
+ booking_intro=(
+ "Tell us about your task so we can show matching Taskers."
+ ),
+ booking_size_legend="Task size",
+ wizard_category_label=str(card["title"]),
+ wizard_start_href=path,
+ status_code=422,
+ )
+ save_draft(
+ request,
+ category=service_slug,
+ apartment_size=size,
+ )
+ return RedirectResponse("/book/help-moving/address", status_code=303)
+
+
+def generic_task_sizes() -> list[dict[str, Any]]:
+ """Return the size choices used by the source-style general task form."""
+ with db_session() as conn:
+ return [
+ dict(row)
+ for row in conn.execute(
+ "SELECT * FROM apartment_sizes WHERE id LIKE 'task-%' "
+ "ORDER BY rowid"
+ ).fetchall()
+ ]
+
+
+def booking_task(category_id: str) -> tuple[dict[str, Any] | None, dict[str, Any] | None]:
+ """Resolve a homepage task or a source-template-aware Service task."""
+ service_task = service_booking_catalog.task(category_id)
+ task = task_catalog.task(category_id) or service_task
+ return task, service_task
+
+
+def booking_task_sizes(service_task: dict[str, Any] | None) -> list[dict[str, Any]]:
+ if service_task is not None:
+ return [dict(row) for row in service_task["size_options"]]
+ return generic_task_sizes()
+
+
+@app.get("/book/task/{category_id}", response_class=HTMLResponse)
+async def generic_task_booking_form(
+ request: Request,
+ category_id: str,
+ state: str = "ready",
+) -> HTMLResponse:
+ task, service_task = booking_task(category_id)
+ if task is None:
+ return not_found_page(request, "We couldn't find that task.")
+ path = f"/book/task/{quote(category_id)}"
+ _account, boundary = booking_requester(request, path)
+ if boundary is not None:
+ return boundary
+ normalized = normalize_state(
+ state,
+ {"ready", "task-size-selected", "validation", "loading", "error"},
+ "ready",
+ )
+ draft = owner_draft(request)
+ sizes = booking_task_sizes(service_task)
+ selected_size = (
+ str(draft.get("apartment_size") or APARTMENT_SIZE)
+ if str(draft.get("category")) == category_id
+ and str(draft.get("apartment_size", "")).startswith("task-")
+ else "task-medium"
+ )
+ return render(
+ request,
+ "book_form.html",
+ page_title=f"Book {task['label']}",
+ state=normalized,
+ errors=(
+ ["Select a valid task size to continue."]
+ if normalized == "validation"
+ else []
+ ),
+ form_category=category_id,
+ form_size=selected_size,
+ booking_sizes=sizes,
+ booking_recommended_size="task-medium",
+ booking_form_action=path,
+ booking_reload_href=path,
+ booking_heading=f"{task['label']} — describe your task",
+ booking_intro=(
+ f"Tell us about your {service_task['source_category_name']} task "
+ "so we can show matching Taskers."
+ if service_task is not None
+ else "Tell us about your task so we can show matching Taskers."
+ ),
+ booking_size_legend=(
+ str(service_task["size_legend"])
+ if service_task is not None
+ else "How big is your task?"
+ ),
+ source_service_booking=service_task,
+ wizard_category_label=str(task["label"]),
+ wizard_start_href=path,
+ )
+
+
+@app.post("/book/task/{category_id}")
+async def generic_task_booking_form_submit(
+ request: Request,
+ category_id: str,
+):
+ task, service_task = booking_task(category_id)
+ if task is None:
+ return not_found_page(request, "We couldn't find that task.")
+ path = f"/book/task/{quote(category_id)}"
+ account, boundary = booking_requester(request, path)
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ size = single(values, "apartment_size")
+ sizes = booking_task_sizes(service_task)
+ valid_sizes = {item["id"] for item in sizes}
+ if size not in valid_sizes:
+ return render(
+ request,
+ "book_form.html",
+ page_title=f"Book {task['label']}",
+ state="validation",
+ errors=["Select a valid task size to continue."],
+ form_category=category_id,
+ form_size=size,
+ booking_sizes=sizes,
+ booking_recommended_size="task-medium",
+ booking_form_action=path,
+ booking_reload_href=path,
+ booking_heading=f"{task['label']} — describe your task",
+ booking_intro=(
+ f"Tell us about your {service_task['source_category_name']} task "
+ "so we can show matching Taskers."
+ if service_task is not None
+ else "Tell us about your task so we can show matching Taskers."
+ ),
+ booking_size_legend=(
+ str(service_task["size_legend"])
+ if service_task is not None
+ else "How big is your task?"
+ ),
+ source_service_booking=service_task,
+ wizard_category_label=str(task["label"]),
+ wizard_start_href=path,
+ status_code=422,
+ )
+ save_draft(
+ request,
+ category=category_id,
+ apartment_size=size,
+ )
+ return RedirectResponse("/book/help-moving/address", status_code=303)
+
+
+@app.get("/dashboard", response_class=HTMLResponse)
+async def book_a_task_dashboard(
+ request: Request,
+ q: str | None = None,
+) -> HTMLResponse:
+ account, boundary = booking_requester(request, "/dashboard")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ query = " ".join((q or "").strip().split())
+ needle = query.casefold()
+ matches: list[dict[str, str]] = []
+ seen_hrefs: set[str] = set()
+ if needle:
+ for task in (*TASKBOOK_QUICK_TASKS, *TASKBOOK_MORE_TASKS, *HOME_TASKS):
+ href = str(task["href"] if "href" in task else task["booking_href"])
+ label = str(task["label"])
+ if needle not in label.casefold() or href in seen_hrefs:
+ continue
+ seen_hrefs.add(href)
+ matches.append({"label": label, "href": href})
+ return render(
+ request,
+ "dashboard.html",
+ page_title="Book your next task",
+ state="results" if query else "ready",
+ dashboard_query=query,
+ dashboard_matches=matches,
+ taskbook_quick_tasks=TASKBOOK_QUICK_TASKS,
+ taskbook_more_tasks=TASKBOOK_MORE_TASKS,
+ taskbook_recommendations=TASKBOOK_RECOMMENDATIONS,
+ )
+
+
+@app.get(
+ "/dashboard/category/{family_id}",
+ response_class=HTMLResponse,
+)
+async def taskbook_category(
+ request: Request,
+ family_id: str,
+) -> HTMLResponse:
+ _account, boundary = booking_requester(
+ request, f"/dashboard/category/{quote(family_id)}"
+ )
+ if boundary is not None:
+ return boundary
+ family = HOME_FAMILY_BY_ID.get(family_id)
+ if family is None:
+ return not_found_page(request, "We couldn't find that task category.")
+ return render(
+ request,
+ "taskbook_category.html",
+ page_title=str(family["label"]),
+ state="task-category",
+ taskbook_family=family,
+ )
+
+
+@app.get(
+ "/dashboard/taskers/{tasker_slug}",
+ response_class=HTMLResponse,
+)
+async def taskbook_tasker_profile(
+ request: Request,
+ tasker_slug: str,
+) -> HTMLResponse:
+ _account, boundary = booking_requester(
+ request, f"/dashboard/taskers/{quote(tasker_slug)}"
+ )
+ if boundary is not None:
+ return boundary
+ tasker = TASKBOOK_RECOMMENDATION_BY_SLUG.get(tasker_slug)
+ if tasker is None:
+ return not_found_page(request, "We couldn't find that Tasker profile.")
+ return render(
+ request,
+ "taskbook_tasker.html",
+ page_title=str(tasker["name"]),
+ state="tasker-profile",
+ taskbook_tasker=tasker,
+ )
+
+
+def dashboard_booking_rows(owner: str) -> list[dict[str, Any]]:
+ """Join persisted owner bookings to their source-facing display facts."""
+ with db_session() as conn:
+ rows = db.list_bookings(conn, owner=owner)
+ taskers = {
+ str(item["id"]): public_tasker(item)
+ for item in db.list_taskers(conn)
+ }
+ categories = {
+ str(item["id"]): dict(item)
+ for item in conn.execute("SELECT * FROM categories").fetchall()
+ }
+ sizes = {
+ str(item["id"]): dict(item)
+ for item in conn.execute("SELECT * FROM apartment_sizes").fetchall()
+ }
+ result: list[dict[str, Any]] = []
+ for booking in reversed(rows):
+ tasker = taskers.get(str(booking["tasker_id"]), {})
+ category = categories.get(str(booking["category"]), {})
+ size = sizes.get(str(booking["apartment_size"]), {})
+ start, _, end = str(booking["window"]).partition("-")
+ result.append(
+ {
+ **booking,
+ "category_label": category.get("label", booking["category"]),
+ "tasker_name": tasker.get("name", TASKER_LABEL),
+ "size_label": size.get("label", booking["apartment_size"]),
+ "date_label": date_label(str(booking["date"])),
+ "window_label": f"{start}–{end}",
+ "total": booking_payments.format_total(
+ booking.get("amount_minor") or 0
+ ),
+ }
+ )
+ return result
+
+
+@app.get("/dashboard/active", response_class=HTMLResponse)
+async def my_tasks_dashboard(
+ request: Request,
+ view: str = "current",
+) -> HTMLResponse:
+ account, boundary = booking_requester(request, "/dashboard/active")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ selected_view = "past" if view == "past" else "current"
+ all_rows = dashboard_booking_rows(account)
+ visible_rows = [
+ row
+ for row in all_rows
+ if (str(row["status"]) == db.BOOKING_STATUS_OPEN)
+ == (selected_view == "current")
+ ]
+ return render(
+ request,
+ "my_tasks.html",
+ page_title="My Tasks",
+ state="tasks" if visible_rows else "empty",
+ task_view=selected_view,
+ bookings=visible_rows,
+ current_count=sum(
+ str(row["status"]) == db.BOOKING_STATUS_OPEN for row in all_rows
+ ),
+ past_count=sum(
+ str(row["status"]) != db.BOOKING_STATUS_OPEN for row in all_rows
+ ),
+ )
+
+
+@app.get("/account/profile", response_class=HTMLResponse)
+async def account_profile(request: Request) -> HTMLResponse:
+ account, boundary = booking_requester(request, "/account/profile")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ auth_session = getattr(request.state, "auth_session", {})
+ auth_account = (
+ auth_session.get("account") if isinstance(auth_session, dict) else {}
+ )
+ principal = current_principal(request) or {}
+ bookings = dashboard_booking_rows(account)
+ return render(
+ request,
+ "account_profile.html",
+ page_title="Account",
+ state="ready",
+ account_name=str(
+ (auth_account or {}).get("display_name")
+ or principal.get("name")
+ or ""
+ ),
+ account_email=str(
+ (auth_account or {}).get("email_normalized")
+ or (auth_account or {}).get("email")
+ or ""
+ ),
+ account_task_count=len(bookings),
+ )
+
+
+@app.get("/out/{destination}", response_class=HTMLResponse)
+async def unobserved_destination(
+ request: Request, destination: str
+) -> HTMLResponse:
+ """Land a control whose source destination the capture never followed.
+
+ Unknown slugs 404 rather than rendering a generic page, so a typo in a
+ template surfaces as a broken route instead of a plausible-looking dead
+ end.
+ """
+ value = EXTERNAL_DESTINATIONS.get(destination)
+ if value is None:
+ return not_found_page(request, "We couldn't find that page.")
+ return render(
+ request,
+ "boundary.html",
+ page_title=str(value["label"]),
+ state="unobserved-destination",
+ destination=value,
+ )
+
+
+@app.get("/services/moving", response_class=HTMLResponse)
+async def moving_landing(request: Request, state: str = "loaded") -> HTMLResponse:
+ normalized = normalize_state(
+ state, {"loaded", "help-moving-card", "book-now", "loading", "error"}, "loaded"
+ )
+ return render(
+ request,
+ "moving.html",
+ page_title="Moving Services",
+ state=normalized,
+ )
+
+
+@app.get("/services/help-moving")
+async def moving_alias() -> RedirectResponse:
+ """Match the captured permanent source redirect to the canonical page."""
+ return RedirectResponse("/services/moving", status_code=308)
+
+
+@app.get("/services/{service_path:path}", response_class=HTMLResponse)
+async def captured_service_destination(
+ request: Request, service_path: str
+) -> HTMLResponse:
+ """Resolve every link frozen on the source services directory.
+
+ Rich pages declared above keep precedence. The remaining captured URLs
+ render a source-derived category or service destination instead of a dead
+ list item or a fabricated booking capability.
+ """
+ path = "/services/" + service_path.strip("/")
+ entry = SERVICE_CATALOG_BY_PATH.get(path)
+ page = SERVICE_PAGES_BY_PATH.get(path)
+ if entry is None or page is None:
+ return not_found_page(request, "We couldn't find that service.")
+ return render(
+ request,
+ "service_catalog_destination.html",
+ page_title=service_source_title(str(page["title"])),
+ meta_description=str(page["meta_description"]),
+ canonical_path=path,
+ state=str(page["family"]),
+ catalog_entry=entry,
+ service_page=page,
+ service_bff=page["bff"],
+ header_variant="furniture-header",
+ )
+
+
+@app.get("/book/help-moving", response_class=HTMLResponse)
+async def booking_form(request: Request, state: str = "ready") -> HTMLResponse:
+ _account, boundary = booking_requester(request, "/book/help-moving")
+ if boundary is not None:
+ return boundary
+ normalized = normalize_state(
+ state, {"ready", "apartment-size-selected", "validation", "loading", "error"}, "ready"
+ )
+ errors = (
+ ["Select a valid apartment size (for example the 1-bedroom apartment) to continue."]
+ if normalized == "validation"
+ else []
+ )
+ draft = owner_draft(request)
+ selected_size = (
+ str(draft.get("apartment_size"))
+ if str(draft.get("category")) == CATEGORY_ID
+ else APARTMENT_SIZE
+ )
+ return render(
+ request,
+ "book_form.html",
+ page_title="Describe your move",
+ state=normalized,
+ errors=errors,
+ form_category=CATEGORY_ID,
+ form_size=selected_size,
+ wizard_category_label=CATEGORY_LABEL,
+ wizard_start_href="/book/help-moving",
+ )
+
+
+@app.post("/book/help-moving")
+async def booking_form_submit(request: Request):
+ account, boundary = booking_requester(request, "/book/help-moving")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ category = single(values, "category")
+ size = single(values, "apartment_size")
+ errors: list[str] = []
+ with db_session() as conn:
+ if category != CATEGORY_ID or db.get_category(conn, category) is None:
+ errors.append(
+ "Unknown task category. Choose one of the offered categories."
+ )
+ if db.get_size(conn, size) is None:
+ errors.append(
+ "Unknown apartment size. Choose one of the offered sizes."
+ )
+ if errors:
+ return render(
+ request,
+ "book_form.html",
+ page_title="Describe your move",
+ state="validation",
+ errors=errors,
+ form_category=category or CATEGORY_ID,
+ form_size=size,
+ wizard_category_label=CATEGORY_LABEL,
+ wizard_start_href="/book/help-moving",
+ status_code=422,
+ )
+ save_draft(request, category=category, apartment_size=size)
+ return RedirectResponse("/book/help-moving/address", status_code=303)
+
+
+@app.get("/book/help-moving/address", response_class=HTMLResponse)
+async def booking_address(request: Request, state: str = "fixture-address-offered") -> HTMLResponse:
+ _account, boundary = booking_requester(
+ request, "/book/help-moving/address"
+ )
+ if boundary is not None:
+ return boundary
+ normalized = normalize_state(
+ state,
+ {"fixture-address-offered", "selected", "validation", "loading", "error"},
+ "fixture-address-offered",
+ )
+ errors = (
+ ["Pick a saved address or add a valid US address."]
+ if normalized == "validation"
+ else []
+ )
+ account = current_account(request)
+ with db_session() as conn:
+ addresses = (
+ [public_address(address) for address in db.list_addresses(conn, account)]
+ if account
+ else []
+ )
+ return render(
+ request,
+ "book_address.html",
+ page_title="Task location",
+ state=normalized,
+ errors=errors,
+ addresses=addresses,
+ address_labeler=db.address_label,
+ )
+
+
+@app.post("/book/help-moving/address")
+async def booking_address_submit(request: Request):
+ account, boundary = booking_requester(request, "/book/help-moving/address")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+
+ def address_page(errors: list[str], status_code: int = 422):
+ with db_session() as conn:
+ addresses = (
+ [
+ public_address(address)
+ for address in db.list_addresses(conn, account)
+ ]
+ if account
+ else []
+ )
+ return render(
+ request,
+ "book_address.html",
+ page_title="Task location",
+ state="validation",
+ errors=errors,
+ addresses=addresses,
+ address_labeler=db.address_label,
+ status_code=status_code,
+ )
+
+ street = single(values, "street").strip()
+ unit = single(values, "unit").strip()
+ city = single(values, "city").strip()
+ state_code = single(values, "state").strip()
+ zip_code = single(values, "zip").strip()
+ address_line = single(values, "address_line").strip()
+ choice = single(values, "address_choice").strip()
+
+ if address_line and not (street or city or state_code or zip_code):
+ parsed = db.parse_address_line(address_line)
+ if parsed is None:
+ return address_page(
+ ["That address could not be parsed. Use "
+ "'street, unit, City ST 12345' or the separate fields."]
+ )
+ street, unit = parsed["street"], parsed["unit"]
+ city, state_code, zip_code = (
+ parsed["city"], parsed["state"], parsed["zip"],
+ )
+
+ if street or city or state_code or zip_code:
+ # New-address path: generic syntactic US-address validation.
+ errors = db.validate_us_address(street, unit, city, state_code, zip_code)
+ if errors:
+ return address_page(errors)
+ with db_session() as conn:
+ address = db.create_address(
+ conn,
+ account,
+ street=street,
+ unit=unit,
+ city=city,
+ state=state_code,
+ zip_code=zip_code,
+ )
+ db.update_draft(conn, account, address_id=address["id"])
+ return RedirectResponse("/book/help-moving/schedule", status_code=303)
+
+ if not choice:
+ return address_page(
+ ["Choose a saved address or enter a new US address."]
+ )
+ with db_session() as conn:
+ owned = owned_address_from_public_id(conn, account, choice)
+ if owned is None:
+ return address_page(
+ ["That is not one of your saved addresses. Add a syntactically "
+ "valid US address or pick one from your address book."]
+ )
+ save_draft(request, address_id=owned["id"])
+ return RedirectResponse("/book/help-moving/schedule", status_code=303)
+
+
+@app.get("/book/help-moving/schedule", response_class=HTMLResponse)
+async def booking_schedule(request: Request, state: str = "frozen-clock-next-saturday") -> HTMLResponse:
+ _account, boundary = booking_requester(
+ request, "/book/help-moving/schedule"
+ )
+ if boundary is not None:
+ return boundary
+ normalized = normalize_state(
+ state,
+ {
+ "frozen-clock-next-saturday",
+ "window-0900-1300-selected",
+ "validation",
+ "loading",
+ "error",
+ },
+ "frozen-clock-next-saturday",
+ )
+ errors = (
+ [
+ "Pick one of the open availability slots: "
+ + (open_slot_summary() or "none are currently open.")
+ ]
+ if normalized == "validation"
+ else []
+ )
+ return render(
+ request,
+ "book_schedule.html",
+ page_title="Pick your time",
+ state=normalized,
+ errors=errors,
+ )
+
+
+@app.post("/book/help-moving/schedule")
+async def booking_schedule_submit(request: Request):
+ account, boundary = booking_requester(request, "/book/help-moving/schedule")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ date = single(values, "date")
+ window = single(values, "window")
+ errors: list[str] = []
+ with db_session() as conn:
+ slot = db.find_slot(conn, date, window)
+ if slot is None:
+ errors.append(
+ "No availability exists for that date and window. Available "
+ f"times: {open_slot_summary() or 'none'}."
+ )
+ elif db.slot_is_past(slot):
+ errors.append("That availability window is in the past and can no longer be booked.")
+ if errors:
+ return render(
+ request,
+ "book_schedule.html",
+ page_title="Pick your time",
+ state="validation",
+ errors=errors,
+ status_code=422,
+ )
+ save_draft(request, slot_id=slot["id"])
+ return RedirectResponse("/book/help-moving/taskers", status_code=303)
+
+
+@app.get("/book/help-moving/taskers", response_class=HTMLResponse)
+async def tasker_list(
+ request: Request, state: str = "simulated-taskers", selected: str = ""
+) -> HTMLResponse:
+ _account, boundary = booking_requester(
+ request, "/book/help-moving/taskers"
+ )
+ if boundary is not None:
+ return boundary
+ normalized = normalize_state(
+ state,
+ {
+ "simulated-taskers",
+ "availability-and-rates",
+ "one-selected",
+ "no-taskers-available",
+ "no-compatible-slot",
+ "loading",
+ "empty",
+ "error",
+ },
+ "simulated-taskers",
+ )
+ tasker_ids = {tasker["id"] for tasker in load_taskers()}
+ selected_id = selected if selected in tasker_ids else ""
+ if normalized == "one-selected" and not selected_id:
+ selected_id = str(owner_draft(request).get("tasker_id") or DEFAULT_TASKER_ID)
+ return render(
+ request,
+ "taskers.html",
+ page_title="Choose your Tasker",
+ state=normalized,
+ selected_id=selected_id,
+ )
+
+
+@app.post("/book/help-moving/taskers")
+async def tasker_select(request: Request):
+ account, boundary = booking_requester(request, "/book/help-moving/taskers")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ tasker_ids = values.get("tasker_id", [])
+ with db_session() as conn:
+ known = {tasker["id"] for tasker in db.list_taskers(conn)}
+ if len(tasker_ids) != 1 or tasker_ids[0] not in known:
+ return render(
+ request,
+ "taskers.html",
+ page_title="Choose your Tasker",
+ state="simulated-taskers",
+ selected_id="",
+ errors=["Select exactly one Tasker."],
+ status_code=422,
+ )
+ with db_session() as conn:
+ draft = db.get_draft(conn, account)
+ if draft and draft.get("slot_id"):
+ if not db.tasker_available(conn, tasker_ids[0], str(draft["slot_id"])):
+ return render(
+ request,
+ "taskers.html",
+ page_title="Choose your Tasker",
+ state="simulated-taskers",
+ selected_id="",
+ errors=["That Tasker has no availability for your selected slot."],
+ status_code=422,
+ )
+ db.update_draft(conn, account, tasker_id=tasker_ids[0])
+ # A new Tasker changes the estimate and fingerprint, so any prior
+ # authorization is stale: force a fresh payment before confirm.
+ db.clear_draft_payment(conn, account)
+ ref = db.ensure_draft(conn, account)["booking_ref"]
+ return RedirectResponse(f"/book/{ref}/payment", status_code=303)
+
+
+def draft_merge_key(
+ conn: Any,
+ *,
+ account: str,
+ session_id: str,
+ draft: dict[str, Any],
+ tasker: dict[str, Any],
+ slot: dict[str, Any],
+) -> dict[str, str]:
+ request_id = str(draft["booking_ref"])
+ request_version = f"request-v{draft['draft_version']}"
+ size = db.get_size(conn, str(draft.get("apartment_size") or APARTMENT_SIZE))
+ if size is None:
+ raise db.BookingInvalid("the drafted apartment size no longer exists")
+ return {
+ "idempotency_token": f"idem-{request_id}-{request_version}",
+ "owner_id": account,
+ "session_id": session_id,
+ "request_id": request_id,
+ "request_version": request_version,
+ "category_id": str(draft.get("category") or CATEGORY_ID),
+ "task_template_id": db.task_template_id_for_category(
+ str(draft.get("category") or CATEGORY_ID)
+ ),
+ "apartment_size_id": str(size["id"]),
+ "apartment_size_version": str(size["version"]),
+ "address_id": str(draft.get("address_id") or ""),
+ "service_date": str(slot["date"]),
+ "window_start": str(slot["window_start"]),
+ "window_end": str(slot["window_end"]),
+ "provider_id": str(tasker["id"]),
+ "provider_version": str(tasker["provider_version"]),
+ "quote_id": (
+ f"quote-{tasker['id']}-{request_id}-{request_version}"
+ ),
+ "quote_version": "quote-v1",
+ "quote_owner_id": account,
+ "slot_id": str(slot["id"]),
+ "slot_version": str(slot["version"]),
+ "payment_flow_id": str(draft.get("payment_flow_id") or ""),
+ }
+
+
+def review_context(
+ account: str,
+ request_id: str,
+ session_id: str,
+ tasker_override: str = "",
+) -> dict[str, Any] | None:
+ """Server-side review facts for an owned request or its existing booking.
+
+ Returns None when the ID belongs to neither the owner's request/draft
+ nor an owned booking.
+ """
+ with db_session() as conn:
+ taskers = {
+ tasker["id"]: public_tasker(tasker)
+ for tasker in db.list_taskers(conn)
+ }
+ booking = db.get_booking_by_request(conn, request_id)
+ draft = db.get_draft(conn, account)
+ open_slots = db.list_open_slots(conn)
+ if booking is not None:
+ if booking["owner"] != account:
+ return {"foreign": True}
+ street_label = booking["address"]
+ slot = db.get_slot(conn, str(booking["slot_id"])) or {
+ "version": booking["slot_version"],
+ "date": booking["date"],
+ "window_start": booking["window"].split("-")[0],
+ "window_end": booking["window"].split("-")[-1],
+ }
+ tasker = taskers.get(str(booking["tasker_id"]))
+ category = db.get_category(conn, str(booking["category"]))
+ size = db.get_size(conn, str(booking["apartment_size"]))
+ return {
+ "already_booked": True,
+ "booking": booking,
+ "request_id": request_id,
+ "merge_key": json.loads(booking["merge_key_json"] or "{}"),
+ "address_label": street_label,
+ "slot": slot,
+ "tasker": tasker or next(iter(taskers.values())),
+ "category_label": category["label"] if category else booking["category"],
+ "size_label": size["label"] if size else booking["apartment_size"],
+ "amount_minor": int(booking.get("amount_minor") or 0),
+ }
+ request_owner = conn.execute(
+ "SELECT owner FROM wizard_drafts WHERE booking_ref=?",
+ (request_id,),
+ ).fetchone()
+ if request_owner is not None and str(request_owner["owner"]) != account:
+ return {"foreign": True}
+ if draft is None or draft["booking_ref"] != request_id:
+ return None
+ slot = (
+ db.get_slot(conn, str(draft["slot_id"]))
+ if draft.get("slot_id")
+ else None
+ ) or (open_slots[0] if open_slots else None)
+ address = (
+ db.get_owned_address(conn, account, str(draft["address_id"]))
+ if draft.get("address_id")
+ else None
+ )
+ if address is None:
+ saved = db.list_addresses(conn, account)
+ address = saved[0] if saved else None
+ tasker_id = tasker_override or str(draft.get("tasker_id") or "")
+ tasker = taskers.get(tasker_id) or taskers.get(DEFAULT_TASKER_ID)
+ category = db.get_category(conn, str(draft.get("category") or CATEGORY_ID))
+ size = db.get_size(conn, str(draft.get("apartment_size") or APARTMENT_SIZE))
+ merge_key = draft_merge_key(
+ conn,
+ account=account,
+ session_id=session_id,
+ draft=draft,
+ tasker=tasker or next(iter(taskers.values())),
+ slot=slot or first_open_slot(),
+ )
+ return {
+ "already_booked": False,
+ "booking": None,
+ "request_id": request_id,
+ "merge_key": merge_key,
+ "address_label": db.address_label(address) if address else "",
+ "slot": slot,
+ "tasker": tasker or next(iter(taskers.values())),
+ "category_label": category["label"] if category else "",
+ "size_label": size["label"] if size else "",
+ "amount_minor": int(draft.get("payment_amount_minor") or 0),
+ }
+
+
+def render_review(
+ request: Request,
+ review: dict[str, Any],
+ request_id: str,
+ *,
+ state: str = "review",
+ errors: list[str] | None = None,
+ status_code: int = 200,
+) -> HTMLResponse:
+ slot = review.get("slot") or first_open_slot()
+ return render(
+ request,
+ "confirm.html",
+ page_title="Review and confirm",
+ state=state,
+ errors=errors or [],
+ tasker=review["tasker"],
+ already_booked=review["already_booked"],
+ request_id=request_id,
+ booking_id=(
+ review["booking"]["id"] if review.get("booking") else None
+ ),
+ merge_key=review["merge_key"],
+ fixture_address=review["address_label"],
+ category_label=review["category_label"] or CATEGORY_LABEL,
+ wizard_category_label=review["category_label"] or CATEGORY_LABEL,
+ apartment_label=review["size_label"] or APARTMENT_LABEL,
+ total=booking_payments.format_total(review.get("amount_minor") or 0),
+ slot_version=slot["version"],
+ window_start=slot["window_start"],
+ window_end=slot["window_end"],
+ next_saturday_iso=slot["date"],
+ next_saturday_label=date_label(slot["date"]),
+ status_code=status_code,
+ )
+
+
+def not_found_page(request: Request, message: str) -> HTMLResponse:
+ return render(
+ request,
+ "error.html",
+ page_title="Not found",
+ state="not-found",
+ message=message,
+ status_code=404,
+ )
+
+
+def foreign_owner_page(request: Request) -> HTMLResponse:
+ return render(
+ request,
+ "error.html",
+ page_title="Access refused",
+ state="foreign-owner",
+ message=(
+ "This booking belongs to another account. "
+ "Sign in with the correct account to view it."
+ ),
+ status_code=403,
+ )
+
+
+def consume_booking_payment(
+ conn: Any,
+ *,
+ flow_id: str,
+ account_id: str,
+ amount_minor: int,
+ fingerprint_value: str,
+) -> None:
+ """Spend the draft's offline-sandbox authorization inside confirm's txn.
+
+ Recomputes the fingerprint from the draft's *current* facts and refuses to
+ consume when they drifted from what was authorized (e.g. the client edited
+ the slot after paying), then delegates to the shared ledger. Translates the
+ payment module's error into ``db.BookingInvalid`` so confirm reports a
+ recoverable, no-booking-created outcome.
+ """
+ draft = db.get_draft(conn, account_id)
+ if draft is None:
+ raise db.BookingInvalid("the booking draft is no longer available")
+ tasker = db.get_tasker(conn, str(draft.get("tasker_id") or ""))
+ if tasker is None:
+ raise db.BookingInvalid("the selected Tasker is no longer available")
+ expected = booking_payments.fingerprint(
+ request_id=str(draft["booking_ref"]),
+ account_id=account_id,
+ category_id=str(draft.get("category") or ""),
+ tasker_id=str(draft["tasker_id"]),
+ slot_id=str(draft.get("slot_id") or ""),
+ amount_minor=booking_payments.estimated_amount_minor(tasker["rate"]),
+ )
+ if expected != fingerprint_value:
+ raise db.BookingInvalid(
+ "the booking changed after payment; authorize the test payment again"
+ )
+ try:
+ booking_payments.consume_authorization(
+ conn,
+ SITE_BACKEND,
+ flow_id=flow_id,
+ account_id=account_id,
+ amount_minor=amount_minor,
+ fingerprint_value=fingerprint_value,
+ )
+ except booking_payments.BookingPaymentError as exc:
+ raise db.BookingInvalid(
+ f"the test payment could not be confirmed: {exc}"
+ ) from exc
+
+
+def payment_context(account: str, request_id: str) -> dict[str, Any] | None:
+ """Server-side payment facts for the owner's in-progress booking draft.
+
+ Returns ``None`` when the request ID is unknown to this owner,
+ ``{"foreign": True}`` when it belongs to another account, ``{"redirect": ...}``
+ when the draft is already booked or not yet ready for payment, else the order
+ summary the payment form renders.
+ """
+ with db_session() as conn:
+ booking = db.get_booking_by_request(conn, request_id)
+ if booking is not None:
+ if booking["owner"] != account:
+ return {"foreign": True}
+ # Already booked: nothing left to authorize; send to the receipt.
+ return {"redirect": f"/bookings/{booking['id']}"}
+ request_owner = conn.execute(
+ "SELECT owner FROM wizard_drafts WHERE booking_ref=?",
+ (request_id,),
+ ).fetchone()
+ if request_owner is not None and str(request_owner["owner"]) != account:
+ return {"foreign": True}
+ draft = db.get_draft(conn, account)
+ if draft is None or draft["booking_ref"] != request_id:
+ return None
+ missing = [
+ field
+ for field in (
+ "category",
+ "apartment_size",
+ "address_id",
+ "slot_id",
+ "tasker_id",
+ )
+ if not draft.get(field)
+ ]
+ if missing:
+ return {"redirect": "/book/help-moving/taskers"}
+ tasker_row = db.get_tasker(conn, str(draft["tasker_id"]))
+ if tasker_row is None:
+ return {"redirect": "/book/help-moving/taskers"}
+ tasker = public_tasker(tasker_row)
+ slot = db.get_slot(conn, str(draft["slot_id"])) or first_open_slot()
+ category = db.get_category(conn, str(draft["category"]))
+ size = db.get_size(conn, str(draft["apartment_size"]))
+ address = db.get_owned_address(conn, account, str(draft["address_id"]))
+ amount_minor = booking_payments.estimated_amount_minor(tasker["rate"])
+ fingerprint_value = booking_payments.fingerprint(
+ request_id=request_id,
+ account_id=account,
+ category_id=str(draft["category"]),
+ tasker_id=str(tasker["id"]),
+ slot_id=str(slot["id"]),
+ amount_minor=amount_minor,
+ )
+ return {
+ "request_id": request_id,
+ "category_id": str(draft["category"]),
+ "tasker": tasker,
+ "slot": slot,
+ "amount_minor": amount_minor,
+ "payment_fingerprint": fingerprint_value,
+ "payment_idempotency_key": (
+ booking_payments.flow_idempotency_key(fingerprint_value)
+ ),
+ "total": booking_payments.format_total(amount_minor),
+ "estimated_hours": booking_payments.ESTIMATED_HOURS,
+ "address_label": db.address_label(address) if address else "",
+ "category_label": category["label"] if category else CATEGORY_LABEL,
+ "size_label": size["label"] if size else APARTMENT_LABEL,
+ "payment_status": str(draft.get("payment_status") or ""),
+ "payment_adapter": booking_payments.payment_adapter(SITE_BACKEND),
+ "scenarios": booking_payments.payment_scenarios(SITE_BACKEND),
+ }
+
+
+def render_payment(
+ request: Request,
+ ctx: dict[str, Any],
+ request_id: str,
+ *,
+ state: str = "pay",
+ errors: list[str] | None = None,
+ status_code: int = 200,
+) -> HTMLResponse:
+ slot = ctx.get("slot") or first_open_slot()
+ return render(
+ request,
+ "payment.html",
+ page_title="Authorize your test payment",
+ state=state,
+ errors=errors or [],
+ request_id=request_id,
+ tasker=ctx["tasker"],
+ category_label=ctx["category_label"],
+ apartment_label=ctx["size_label"],
+ fixture_address=ctx["address_label"],
+ slot_version=slot["version"],
+ window_start=slot["window_start"],
+ window_end=slot["window_end"],
+ next_saturday_iso=slot["date"],
+ next_saturday_label=date_label(slot["date"]),
+ amount_minor=ctx["amount_minor"],
+ total=ctx["total"],
+ estimated_hours=ctx["estimated_hours"],
+ scenarios=ctx["scenarios"],
+ payment_status=ctx["payment_status"],
+ payment_adapter=ctx["payment_adapter"],
+ payment_idempotency_key=ctx["payment_idempotency_key"],
+ status_code=status_code,
+ )
+
+
+@app.get("/book/{request_id}/payment", response_class=HTMLResponse)
+async def booking_payment(
+ request: Request,
+ request_id: str,
+ payment: str | None = None,
+) -> HTMLResponse:
+ account, boundary = booking_requester(
+ request, f"/book/{request_id}/payment"
+ )
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ ctx = payment_context(account, request_id)
+ if ctx is None:
+ return not_found_page(
+ request, "We couldn't find this booking request."
+ )
+ if ctx.get("foreign"):
+ return foreign_owner_page(request)
+ if ctx.get("redirect"):
+ return RedirectResponse(str(ctx["redirect"]), status_code=303)
+ if payment == "cancelled":
+ return render_payment(
+ request,
+ ctx,
+ request_id,
+ state="cancelled",
+ errors=["Stripe test Checkout was cancelled. No payment was recorded."],
+ )
+ if payment == "declined":
+ return render_payment(
+ request,
+ ctx,
+ request_id,
+ state="declined",
+ errors=[
+ "Stripe could not verify this test payment. No booking was created."
+ ],
+ )
+ return render_payment(request, ctx, request_id)
+
+
+@app.post("/book/{request_id}/payment")
+async def booking_payment_submit(request: Request, request_id: str):
+ account, boundary = booking_requester(
+ request, f"/book/{request_id}/payment"
+ )
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ ctx = payment_context(account, request_id)
+ if ctx is None:
+ return not_found_page(
+ request, "We couldn't find this booking request."
+ )
+ if ctx.get("foreign"):
+ return foreign_owner_page(request)
+ if ctx.get("redirect"):
+ return RedirectResponse(str(ctx["redirect"]), status_code=303)
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ submitted_payment_key = single(values, "idempotency_key")
+ if (
+ submitted_payment_key
+ and submitted_payment_key != ctx["payment_idempotency_key"]
+ ):
+ return render_payment(
+ request,
+ ctx,
+ request_id,
+ errors=["The payment form expired. Reload it and try again."],
+ status_code=409,
+ )
+ if ctx["payment_adapter"] == "stripe-test":
+ try:
+ with db_session(immediate=True) as conn:
+ flow = booking_payments.create_or_reuse_stripe_flow(
+ conn,
+ SITE_BACKEND,
+ account_id=account,
+ amount_minor=int(ctx["amount_minor"]),
+ fingerprint_value=str(ctx["payment_fingerprint"]),
+ )
+ db.set_draft_payment(
+ conn,
+ account,
+ flow_id=str(flow["flow_id"]),
+ amount_minor=int(ctx["amount_minor"]),
+ currency=booking_payments.CURRENCY,
+ fingerprint=str(ctx["payment_fingerprint"]),
+ status="PENDING",
+ )
+ provider = StripeTestGateway(SITE_BACKEND.config).create_checkout_session(
+ flow=flow,
+ customer_email=current_account_email(request),
+ line_items=(
+ StripeTestLineItem(
+ name=f"Taskrabbit test booking — {ctx['category_label']}",
+ amount_minor=int(ctx["amount_minor"]),
+ ),
+ ),
+ )
+ return RedirectResponse(str(provider["url"]), status_code=303)
+ except (
+ booking_payments.BookingPaymentError,
+ StripeTestError,
+ StripeTestResponseError,
+ StripeTestUnavailable,
+ ):
+ return render_payment(
+ request,
+ ctx,
+ request_id,
+ errors=[
+ "Stripe test Checkout is temporarily unavailable. Try again."
+ ],
+ status_code=503,
+ )
+
+ scenario_id = single(values, "scenario")
+ if scenario_id not in booking_payments.scenario_ids(SITE_BACKEND):
+ return render_payment(
+ request,
+ ctx,
+ request_id,
+ errors=["Choose a test payment outcome to continue."],
+ status_code=422,
+ )
+ amount_minor = int(ctx["amount_minor"])
+ fingerprint_value = str(ctx["payment_fingerprint"])
+ try:
+ with db_session(immediate=True) as conn:
+ flow_id = booking_payments.create_or_reuse_flow(
+ conn,
+ SITE_BACKEND,
+ account_id=account,
+ amount_minor=amount_minor,
+ fingerprint_value=fingerprint_value,
+ )
+ outcome = booking_payments.attempt_local_payment(
+ conn,
+ SITE_BACKEND,
+ flow_id=flow_id,
+ account_id=account,
+ amount_minor=amount_minor,
+ fingerprint_value=fingerprint_value,
+ scenario_id=scenario_id,
+ )
+ db.set_draft_payment(
+ conn,
+ account,
+ flow_id=flow_id,
+ amount_minor=amount_minor,
+ currency=booking_payments.CURRENCY,
+ fingerprint=fingerprint_value,
+ status=outcome.upper(),
+ )
+ except booking_payments.BookingPaymentError as exc:
+ return render_payment(
+ request,
+ ctx,
+ request_id,
+ errors=[f"The test payment could not be processed: {exc}."],
+ status_code=422,
+ )
+ if outcome == "approved":
+ return RedirectResponse(
+ f"/book/{request_id}/confirm", status_code=303
+ )
+ # Non-approved: the draft now records the outcome, so confirm stays gated.
+ # Re-render the form (payment doesn't change draft identity) with the result.
+ refreshed = payment_context(account, request_id)
+ if (
+ not isinstance(refreshed, dict)
+ or refreshed.get("redirect")
+ or refreshed.get("foreign")
+ ):
+ refreshed = ctx
+ message = {
+ "declined": "The test payment was declined. Choose an outcome to try again.",
+ "retryable": "The test payment needs another attempt. Choose an outcome to retry.",
+ }.get(outcome, "Choose a test payment outcome to continue.")
+ return render_payment(
+ request,
+ refreshed,
+ request_id,
+ state="retry" if outcome == "retryable" else "declined",
+ errors=[message],
+ )
+
+
+def _owner_payment_path(account: str) -> str:
+ with db_session() as conn:
+ draft = db.get_draft(conn, account)
+ if draft and draft.get("booking_ref"):
+ return f"/book/{draft['booking_ref']}/payment"
+ return "/book/help-moving/taskers"
+
+
+def _approve_stripe_booking(
+ provider_session_id: str,
+ provider_snapshot: Mapping[str, Any],
+ *,
+ expected_account: str | None = None,
+) -> dict[str, str]:
+ metadata = provider_snapshot.get("metadata")
+ if not isinstance(metadata, Mapping):
+ raise booking_payments.BookingPaymentError(
+ "Stripe test Session metadata is unavailable"
+ )
+ account = str(metadata.get("owner") or "")
+ flow_id = str(metadata.get("flow_id") or "")
+ if expected_account is not None and account != expected_account:
+ raise booking_payments.BookingPaymentError(
+ "Stripe test Session belongs to another account"
+ )
+ with db_session(immediate=True) as conn:
+ draft = db.get_draft(conn, account)
+ if draft is None or str(draft.get("payment_flow_id") or "") != flow_id:
+ booked = conn.execute(
+ "SELECT id,request_id FROM bookings WHERE payment_flow_id=?",
+ (flow_id,),
+ ).fetchone()
+ if booked is not None:
+ return {
+ "account": account,
+ "request_id": str(booked["request_id"]),
+ "booking_id": str(booked["id"]),
+ }
+ raise booking_payments.BookingPaymentError(
+ "Stripe test payment flow is no longer active"
+ )
+ amount_minor = int(draft.get("payment_amount_minor") or 0)
+ fingerprint_value = str(draft.get("payment_fingerprint") or "")
+ status = booking_payments.approve_verified_stripe(
+ conn,
+ SITE_BACKEND,
+ flow_id=flow_id,
+ account_id=account,
+ amount_minor=amount_minor,
+ fingerprint_value=fingerprint_value,
+ provider_session_id=provider_session_id,
+ provider_snapshot=provider_snapshot,
+ )
+ if status != "approved":
+ raise booking_payments.BookingPaymentError(
+ "Stripe test payment was not approved"
+ )
+ db.set_draft_payment(
+ conn,
+ account,
+ flow_id=flow_id,
+ amount_minor=amount_minor,
+ currency=booking_payments.CURRENCY,
+ fingerprint=fingerprint_value,
+ status="APPROVED",
+ )
+ return {
+ "account": account,
+ "request_id": str(draft["booking_ref"]),
+ }
+
+
+@app.get("/book/stripe-return")
+async def booking_stripe_return(request: Request):
+ account, boundary = booking_requester(request, "/book/help-moving/taskers")
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ if request.query_params.get("cancelled") == "1":
+ return RedirectResponse(
+ f"{_owner_payment_path(account)}?payment=cancelled",
+ status_code=303,
+ )
+ provider_session_id = request.query_params.get("session_id", "")
+ try:
+ provider_snapshot = StripeTestGateway(
+ SITE_BACKEND.config
+ ).retrieve_checkout_session(provider_session_id)
+ result = _approve_stripe_booking(
+ provider_session_id,
+ provider_snapshot,
+ expected_account=account,
+ )
+ except (
+ booking_payments.BookingPaymentError,
+ StripeTestError,
+ StripeTestResponseError,
+ StripeTestUnavailable,
+ ):
+ return RedirectResponse(
+ f"{_owner_payment_path(account)}?payment=declined",
+ status_code=303,
+ )
+ if result.get("booking_id"):
+ return RedirectResponse(
+ f"/bookings/{result['booking_id']}", status_code=303
+ )
+ return RedirectResponse(
+ f"/book/{result['request_id']}/confirm", status_code=303
+ )
+
+
+@app.post("/api/stripe/webhook")
+async def booking_stripe_webhook(request: Request) -> JSONResponse:
+ if request.headers.get("x-websitebench-stripe-verified") != "1":
+ return JSONResponse({"received": False}, status_code=400)
+ raw = await request.body()
+ if not raw or len(raw) > 64 * 1024:
+ return JSONResponse({"received": False}, status_code=400)
+ try:
+ event = json.loads(raw.decode("utf-8"))
+ if not isinstance(event, dict):
+ raise ValueError("event is invalid")
+ if event.get("type") == "checkout.session.expired":
+ return JSONResponse({"received": True})
+ data = event.get("data")
+ session = data.get("object") if isinstance(data, dict) else None
+ provider_session_id = (
+ session.get("id") if isinstance(session, dict) else None
+ )
+ if (
+ event.get("type") != "checkout.session.completed"
+ or not isinstance(provider_session_id, str)
+ ):
+ raise ValueError("event is invalid")
+ provider_snapshot = StripeTestGateway(
+ SITE_BACKEND.config
+ ).retrieve_checkout_session(provider_session_id)
+ _approve_stripe_booking(provider_session_id, provider_snapshot)
+ except (
+ ValueError,
+ UnicodeDecodeError,
+ booking_payments.BookingPaymentError,
+ StripeTestError,
+ StripeTestResponseError,
+ StripeTestUnavailable,
+ ):
+ return JSONResponse({"received": False}, status_code=400)
+ return JSONResponse({"received": True})
+
+
+@app.get("/book/{request_id}/confirm", response_class=HTMLResponse)
+async def booking_review(
+ request: Request, request_id: str, state: str = "review", tasker: str = ""
+) -> HTMLResponse:
+ account, boundary = booking_requester(
+ request, f"/book/{request_id}/confirm"
+ )
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ session_id = session_binding(request)
+ review = review_context(account, request_id, session_id, tasker)
+ if review is None:
+ return not_found_page(
+ request, "We couldn't find this booking request."
+ )
+ if review.get("foreign"):
+ return foreign_owner_page(request)
+ normalized = normalize_state(
+ state,
+ {"review", "confirming", "stale-slot-conflict", "duplicate-rejected"},
+ "review",
+ )
+ status_code = 409 if normalized == "stale-slot-conflict" else 200
+ return render_review(
+ request, review, request_id, state=normalized, status_code=status_code
+ )
+
+
+@app.post("/book/{request_id}/confirm")
+async def booking_confirm(request: Request, request_id: str):
+ account, boundary = booking_requester(
+ request, f"/book/{request_id}/confirm"
+ )
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ session_id = session_binding(request)
+ review = review_context(account, request_id, session_id)
+ if review is None:
+ return not_found_page(
+ request, "We couldn't find this booking request."
+ )
+ if review.get("foreign"):
+ return foreign_owner_page(request)
+ values = await urlencoded_form(request)
+ submitted_merge_key = {
+ field: single(values, field)
+ for field in db.CONFIRM_MERGE_KEY_FIELDS
+ }
+ tasker_ids = values.get("provider_id", [])
+ if single(values, "csrf") != CSRF_VALUE:
+ return render_review(
+ request,
+ review,
+ request_id,
+ errors=["The form expired. Reload the review page and try again."],
+ status_code=403,
+ )
+ with db_session() as conn:
+ known = {tasker["id"] for tasker in db.list_taskers(conn)}
+ if len(tasker_ids) != 1 or tasker_ids[0] not in known:
+ return render_review(
+ request,
+ review,
+ request_id,
+ errors=["Select exactly one Tasker before confirming."],
+ status_code=422,
+ )
+ try:
+ with db_session(immediate=True) as conn:
+ booking, created = db.confirm_booking(
+ conn,
+ owner=account,
+ request_id=request_id,
+ submitted_merge_key=submitted_merge_key,
+ payment_consumer=consume_booking_payment,
+ )
+ except db.BookingConflict as conflict:
+ return render_review(
+ request,
+ review_context(
+ account, request_id, session_id, tasker_ids[0]
+ )
+ or review,
+ request_id,
+ state="stale-slot-conflict",
+ errors=[
+ f"Slot version conflict: {conflict}; your review page is "
+ "stale. No booking was created."
+ ],
+ status_code=409,
+ )
+ except db.BookingInvalid as invalid:
+ return render_review(
+ request,
+ review,
+ request_id,
+ errors=[f"Cannot confirm: {invalid}. No booking was created."],
+ status_code=422,
+ )
+ except db.BookingUnauthorized:
+ return render_review(
+ request,
+ review,
+ request_id,
+ errors=["This account cannot submit booking requests."],
+ status_code=403,
+ )
+ if not created:
+ # Exact retry: the request/size/provider/quote/slot tuple maps to the
+ # post-confirm booking ID already minted by the first mutation.
+ return RedirectResponse(
+ f"/bookings/{booking['id']}?state=refresh", status_code=303
+ )
+ return RedirectResponse(f"/bookings/{booking['id']}", status_code=303)
+
+
+@app.get("/bookings/{booking_ref}", response_class=HTMLResponse)
+async def booking_receipt(
+ request: Request, booking_ref: str, state: str = "local-success"
+) -> HTMLResponse:
+ account, boundary = booking_requester(
+ request, f"/bookings/{booking_ref}"
+ )
+ if boundary is not None:
+ return boundary
+ assert account is not None
+ with db_session() as conn:
+ booked = db.get_booking(conn, booking_ref)
+ taskers = {
+ tasker["id"]: public_tasker(tasker)
+ for tasker in db.list_taskers(conn)
+ }
+ category = (
+ db.get_category(conn, str(booked["category"])) if booked else None
+ )
+ size = (
+ db.get_size(conn, str(booked["apartment_size"]))
+ if booked
+ else None
+ )
+ if booked is None:
+ return not_found_page(
+ request, "We couldn't find this booking."
+ )
+ if booked["owner"] != account:
+ return foreign_owner_page(request)
+ normalized = normalize_state(
+ state,
+ {"local-success", "refresh", "restart-durable", "simulation-disclosure"},
+ "local-success",
+ )
+ tasker = taskers.get(str(booked["tasker_id"])) or next(iter(taskers.values()))
+ tasker = dict(tasker)
+ tasker["rate"] = int(booked["hourly_rate"])
+ window_start, _, window_end = str(booked["window"]).partition("-")
+ return render(
+ request,
+ "receipt.html",
+ page_title="Booking details",
+ state=normalized,
+ tasker=tasker,
+ booking_id=booked["id"],
+ request_id=booked["request_id"],
+ receipt_id=booked["receipt_id"],
+ request_version=booked["request_version"],
+ category_label=category["label"] if category else booked["category"],
+ booking_again_href=booking_href_for_category(str(booked["category"])),
+ total=booking_payments.format_total(booked.get("amount_minor") or 0),
+ apartment_size_id=booked["apartment_size"],
+ apartment_size_version=booked["apartment_size_version"],
+ apartment_label=(
+ size["label"] if size else booked["apartment_size"]
+ ),
+ quote_id=booked["quote_id"],
+ quote_version=booked["quote_version"],
+ fixture_address=booked["address"],
+ slot_version=booked["slot_version"],
+ window_start=window_start,
+ window_end=window_end,
+ next_saturday_iso=booked["date"],
+ next_saturday_label=date_label(str(booked["date"])),
+ restart_durable=False,
+ )
+
+
+@app.get("/login", response_class=HTMLResponse)
+@app.get("/auth/login", response_class=HTMLResponse)
+async def login(request: Request, next: str | None = None, state: str = "") -> HTMLResponse:
+ if signed_in(request):
+ normalized = "signed-in"
+ elif state == "unauthorized":
+ normalized = "unauthorized"
+ else:
+ normalized = "credentials"
+ return render(
+ request,
+ "login.html",
+ page_title="Sign up or log in",
+ state=normalized,
+ next_path=safe_next(next, request),
+ unauthorized=normalized == "unauthorized",
+ )
+
+
+def auth_error_message(error: AuthError) -> str:
+ if isinstance(error, AuthRateLimited):
+ return "Please wait before requesting another message."
+ if isinstance(error, AuthConflict):
+ return "That email cannot be used for this request."
+ if isinstance(error, AuthValidationError):
+ return str(error)
+ return "We couldn't complete that request. Check the details and try again."
+
+
+def auth_subject_factory(connection, registration) -> str:
+ account_id = str(registration["account_id"])
+ subject_id = "requester-" + hashlib.sha256(
+ account_id.encode("utf-8")
+ ).hexdigest()[:24]
+ connection.execute(
+ "INSERT INTO clients(id,display_name,role) VALUES (?,?,'requester')",
+ (subject_id, str(registration["display_name"])),
+ )
+ return subject_id
+
+
+@app.post("/auth/sign-in")
+@app.post("/auth/login")
+async def auth_sign_in(request: Request):
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "login.html",
+ page_title="Sign up or log in",
+ state="unauthorized",
+ next_path=safe_next(single(values, "next"), request),
+ unauthorized=True,
+ errors=["Your sign-in form expired. Please try again."],
+ status_code=403,
+ )
+ try:
+ result = AUTH_STORE.sign_in(
+ request.state.auth_token,
+ # The captured source form names this field `username`; older
+ # callers and tests post `email`. Both are accepted so the
+ # rendered field can carry the source's own name.
+ email=single(values, "email") or single(values, "username"),
+ password=single(values, "password"),
+ )
+ except AuthError:
+ return render(
+ request,
+ "login.html",
+ page_title="Sign up or log in",
+ state="unauthorized",
+ next_path=safe_next(single(values, "next"), request),
+ unauthorized=True,
+ errors=["Email or password is invalid."],
+ status_code=401,
+ )
+ token = str(result["session_token"])
+ request.state.auth_token = token
+ request.state.auth_session = AUTH_STORE.resolve_session(token)
+ response = RedirectResponse(
+ safe_next(single(values, "next"), request), status_code=303
+ )
+ return response
+
+
+@app.post("/api/auth/send-code", include_in_schema=False)
+async def public_registration_send_code(request: Request) -> JSONResponse:
+ return await send_registration_code(
+ request,
+ verification=PUBLIC_REGISTRATION_VERIFICATION,
+ store=AUTH_STORE,
+ session_token=str(request.state.auth_token),
+ )
+
+
+@app.post("/api/auth/verify-code", include_in_schema=False)
+async def public_registration_verify_code(request: Request) -> JSONResponse:
+ return await verify_registration_code(
+ request,
+ verification=PUBLIC_REGISTRATION_VERIFICATION,
+ store=AUTH_STORE,
+ session_token=str(request.state.auth_token),
+ )
+
+
+@app.get("/register", response_class=HTMLResponse)
+@app.get("/auth/register", response_class=HTMLResponse)
+async def register(request: Request, next: str | None = None) -> HTMLResponse:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=safe_next(next, request),
+ errors=[],
+ )
+
+
+@app.post("/register")
+@app.post("/auth/register")
+async def register_start(request: Request):
+ values = await urlencoded_form(request)
+ next_path = safe_next(single(values, "next"), request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=["Your registration form expired. Please try again."],
+ status_code=403,
+ )
+ profile_errors = registration_profile_errors(values)
+ if profile_errors:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=profile_errors,
+ status_code=422,
+ **registration_form_values(values),
+ )
+ if PUBLIC_REGISTRATION_VERIFICATION is not None:
+ try:
+ AUTH_STORE.validate_registration_details(
+ email=single(values, "email"),
+ display_name=registration_display_name(values),
+ password=single(values, "password"),
+ )
+ ticket = consume_registration_ticket(
+ verification=PUBLIC_REGISTRATION_VERIFICATION,
+ store=AUTH_STORE,
+ session_token=str(request.state.auth_token),
+ email=single(values, "email"),
+ )
+ if not ticket:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=["Verify this email address before creating the account."],
+ status_code=422,
+ )
+ result = AUTH_STORE.complete_externally_verified_registration(
+ str(request.state.auth_token),
+ email=single(values, "email"),
+ display_name=registration_display_name(values),
+ password=single(values, "password"),
+ subject_factory=auth_subject_factory,
+ )
+ except VerificationUnavailable:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=["Email verification is temporarily unavailable."],
+ status_code=503,
+ )
+ except AuthError as error:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=[auth_error_message(error)],
+ status_code=422,
+ )
+ token = str(result["session_token"])
+ request.state.auth_token = token
+ request.state.auth_session = AUTH_STORE.resolve_session(token)
+ return RedirectResponse(next_path, status_code=303)
+ try:
+ AUTH_STORE.start_registration(
+ request.state.auth_token,
+ email=single(values, "email"),
+ display_name=registration_display_name(values),
+ password=single(values, "password"),
+ )
+ except AuthRateLimited as error:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=[auth_error_message(error)],
+ status_code=429,
+ )
+ except AuthError as error:
+ return render(
+ request,
+ "register.html",
+ page_title="Create your account",
+ next_path=next_path,
+ errors=[auth_error_message(error)],
+ status_code=422,
+ )
+ return RedirectResponse(
+ f"/auth/register/verify?next={quote(next_path, safe='/')}",
+ status_code=303,
+ )
+
+
+@app.get("/register/verify", response_class=HTMLResponse)
+@app.get("/auth/register/verify", response_class=HTMLResponse)
+async def register_verify_page(
+ request: Request, next: str | None = None
+) -> HTMLResponse:
+ flow = AUTH_STORE.session_flow_status(
+ request.state.auth_token, purpose="registration"
+ )
+ return render(
+ request,
+ "verify.html",
+ page_title="Verify your email",
+ purpose="registration",
+ state=str(flow["state"]),
+ next_path=safe_next(next, request),
+ errors=[],
+ )
+
+
+@app.post("/register/verify")
+@app.post("/auth/register/verify")
+async def register_verify(request: Request):
+ values = await urlencoded_form(request)
+ next_path = safe_next(single(values, "next"), request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "verify.html",
+ page_title="Verify your email",
+ purpose="registration",
+ state="challenge",
+ next_path=next_path,
+ errors=["Your verification form expired. Please try again."],
+ status_code=403,
+ )
+ try:
+ AUTH_STORE.verify_registration_code(
+ request.state.auth_token,
+ single(values, "code"),
+ )
+ result = AUTH_STORE.complete_registration(
+ request.state.auth_token,
+ subject_factory=auth_subject_factory,
+ )
+ except AuthError as error:
+ return render(
+ request,
+ "verify.html",
+ page_title="Verify your email",
+ purpose="registration",
+ state=str(
+ AUTH_STORE.session_flow_status(
+ request.state.auth_token, purpose="registration"
+ )["state"]
+ ),
+ next_path=next_path,
+ errors=[auth_error_message(error)],
+ status_code=422,
+ )
+ token = str(result["session_token"])
+ request.state.auth_token = token
+ request.state.auth_session = AUTH_STORE.resolve_session(token)
+ return RedirectResponse(next_path, status_code=303)
+
+
+@app.get("/recover", response_class=HTMLResponse)
+@app.get("/auth/password/forgot", response_class=HTMLResponse)
+async def recover(request: Request) -> HTMLResponse:
+ return render(
+ request,
+ "recover.html",
+ page_title="Reset your password",
+ state="request",
+ message="",
+ errors=[],
+ )
+
+
+@app.post("/recover")
+@app.post("/auth/password/forgot")
+async def recover_start(request: Request):
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "recover.html",
+ page_title="Reset your password",
+ state="request",
+ message="",
+ errors=["Your recovery form expired. Please try again."],
+ status_code=403,
+ )
+ try:
+ result = AUTH_STORE.start_password_reset(
+ request.state.auth_token,
+ email=single(values, "email"),
+ )
+ message = str(result["message"])
+ except AuthRateLimited:
+ message = RESET_PUBLIC_MESSAGE
+ except AuthValidationError as error:
+ return render(
+ request,
+ "recover.html",
+ page_title="Reset your password",
+ state="request",
+ message="",
+ errors=[str(error)],
+ status_code=422,
+ )
+ return render(
+ request,
+ "recover.html",
+ page_title="Reset your password",
+ state="request",
+ message=message,
+ errors=[],
+ )
+
+
+@app.get("/auth/password/verify", response_class=HTMLResponse)
+async def password_verify_page(request: Request) -> HTMLResponse:
+ flow = AUTH_STORE.session_flow_status(
+ request.state.auth_token, purpose="password-reset"
+ )
+ return render(
+ request,
+ "recover.html",
+ page_title="Verify your reset code",
+ state="verify-code",
+ flow_state=str(flow["state"]),
+ message=RESET_PUBLIC_MESSAGE,
+ errors=[],
+ )
+
+
+@app.post("/auth/password/verify")
+async def password_verify(request: Request):
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "recover.html",
+ page_title="Verify your reset code",
+ state="verify-code",
+ flow_state="challenge",
+ message=RESET_PUBLIC_MESSAGE,
+ errors=["Your recovery form expired. Please try again."],
+ status_code=403,
+ )
+ try:
+ AUTH_STORE.verify_password_reset_code(
+ request.state.auth_token,
+ single(values, "code"),
+ )
+ except AuthError as error:
+ flow = AUTH_STORE.session_flow_status(
+ request.state.auth_token, purpose="password-reset"
+ )
+ return render(
+ request,
+ "recover.html",
+ page_title="Verify your reset code",
+ state="verify-code",
+ flow_state=str(flow["state"]),
+ message=RESET_PUBLIC_MESSAGE,
+ errors=[auth_error_message(error)],
+ status_code=422,
+ )
+ return RedirectResponse("/auth/password/reset", status_code=303)
+
+
+@app.get("/auth/password/reset", response_class=HTMLResponse)
+async def password_reset_page(request: Request) -> HTMLResponse:
+ flow = AUTH_STORE.session_flow_status(
+ request.state.auth_token, purpose="password-reset"
+ )
+ verified = flow["state"] == "verified"
+ return render(
+ request,
+ "recover.html",
+ page_title="Choose a new password",
+ state="reset-password" if verified else "restart",
+ flow_state=str(flow["state"]),
+ message="" if verified else "Start password recovery again to continue.",
+ errors=[],
+ status_code=200 if verified else 409,
+ )
+
+
+@app.post("/auth/password/reset")
+async def password_reset(request: Request):
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "recover.html",
+ page_title="Choose a new password",
+ state="reset-password",
+ flow_state="verified",
+ message="",
+ errors=["Your recovery form expired. Please try again."],
+ status_code=403,
+ )
+ try:
+ token = AUTH_STORE.complete_password_reset(
+ request.state.auth_token,
+ new_password=single(values, "new_password"),
+ )
+ except AuthRejected as error:
+ return render(
+ request,
+ "recover.html",
+ page_title="Choose a new password",
+ state="restart",
+ flow_state="stale",
+ message="Start password recovery again to continue.",
+ errors=[auth_error_message(error)],
+ status_code=409,
+ )
+ except AuthError as error:
+ return render(
+ request,
+ "recover.html",
+ page_title="Choose a new password",
+ state="reset-password",
+ flow_state="verified",
+ message="",
+ errors=[auth_error_message(error)],
+ status_code=422,
+ )
+ request.state.auth_token = token
+ request.state.auth_session = AUTH_STORE.resolve_session(token)
+ return RedirectResponse("/auth/login", status_code=303)
+
+
+@app.post("/recover/complete")
+async def recover_complete(request: Request):
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return render(
+ request,
+ "recover.html",
+ page_title="Reset your password",
+ state="verify",
+ message=RESET_PUBLIC_MESSAGE,
+ errors=["Your recovery form expired. Please try again."],
+ status_code=403,
+ )
+ try:
+ AUTH_STORE.verify_password_reset_code(
+ request.state.auth_token,
+ single(values, "code"),
+ )
+ token = AUTH_STORE.complete_password_reset(
+ request.state.auth_token,
+ new_password=single(values, "new_password"),
+ )
+ except AuthError as error:
+ return render(
+ request,
+ "recover.html",
+ page_title="Reset your password",
+ state="verify",
+ message=RESET_PUBLIC_MESSAGE,
+ errors=[auth_error_message(error)],
+ status_code=422,
+ )
+ request.state.auth_token = token
+ request.state.auth_session = AUTH_STORE.resolve_session(token)
+ return RedirectResponse("/", status_code=303)
+
+
+@app.get("/auth/inbox", response_class=HTMLResponse)
+@app.get("/auth/local-inbox", response_class=HTMLResponse)
+async def auth_inbox(
+ request: Request, purpose: str = "registration"
+) -> HTMLResponse:
+ selected = (
+ "password-reset"
+ if purpose == "password-reset"
+ else "registration"
+ )
+ message = AUTH_STORE.local_mail_for_session(
+ request.state.auth_token,
+ purpose=selected,
+ )
+ delivery = AUTH_STORE.session_mail_state(
+ request.state.auth_token,
+ purpose=selected,
+ )
+ public_delivery = {
+ "LOCAL_ONLY": "Verification message",
+ "SMTP_PENDING": "Message queued",
+ "SMTP_SENT": "Message sent",
+ "SMTP_FAILED": "We couldn't send this message",
+ }.get(str(delivery["status"]) if delivery else "", "No message is available")
+ return render(
+ request,
+ "inbox.html",
+ page_title="Verification message",
+ purpose=selected,
+ message=message,
+ public_delivery=public_delivery,
+ )
+
+
+@app.post("/auth/sign-out")
+@app.post("/auth/logout")
+async def auth_sign_out(request: Request):
+ values = await urlencoded_form(request)
+ if single(values, "csrf") != CSRF_VALUE:
+ return csrf_forbidden_page(request)
+ AUTH_STORE.sign_out(request.state.auth_token)
+ token = AUTH_STORE.create_anonymous_session()
+ request.state.auth_token = token
+ request.state.auth_session = AUTH_STORE.resolve_session(token)
+ return RedirectResponse("/", status_code=303)
+
+
+def main() -> None:
+ port = int(os.environ.get("PORT", "8452"))
+ uvicorn.run(app, host="127.0.0.1", port=port, access_log=True)
+
+
+if __name__ == "__main__":
+ main()