"""Source-grounded Blue Apron offline review clone.""" from __future__ import annotations import json import re import sqlite3 from pathlib import Path from fastapi import FastAPI, Request from fastapi.responses import FileResponse, HTMLResponse, JSONResponse from backend.site_backend_integration import open_site_services from websitebench.local_clone_auth import AuthError ROOT = Path(__file__).resolve().parent RECIPES = json.loads((ROOT / "recipes.json").read_text(encoding="utf-8")) BY_ID = {item["id"]: item for item in RECIPES} BY_SLUG = {item["slug"]: item for item in RECIPES} WEEKLY = RECIPES[:48] ADDONS = { "breakfast": {"name": "Blueberry Overnight Oats", "price": 8.99}, "snack": {"name": "Chocolate Chip Oat Cookies", "price": 6.99}, "protein": {"name": "Extra Garlic-Herb Chicken", "price": 11.99}, } app = FastAPI(title="Blue Apron Offline Clone") def database(): backend, _ = open_site_services() connection = sqlite3.connect(backend.lifecycle.database_path) connection.row_factory = sqlite3.Row connection.executescript( """ CREATE TABLE IF NOT EXISTS ba_plan( session TEXT PRIMARY KEY, servings INTEGER NOT NULL DEFAULT 2, meals INTEGER NOT NULL DEFAULT 3, preference TEXT NOT NULL DEFAULT 'All' ); CREATE TABLE IF NOT EXISTS ba_cart( session TEXT NOT NULL, recipe_id TEXT NOT NULL, qty INTEGER NOT NULL DEFAULT 1, upgrade TEXT NOT NULL DEFAULT '', PRIMARY KEY(session,recipe_id) ); CREATE TABLE IF NOT EXISTS ba_addons( session TEXT NOT NULL, addon_id TEXT NOT NULL, qty INTEGER NOT NULL DEFAULT 1, PRIMARY KEY(session,addon_id) ); CREATE TABLE IF NOT EXISTS ba_delivery( session TEXT PRIMARY KEY, name TEXT NOT NULL DEFAULT '', address TEXT NOT NULL DEFAULT '', city TEXT NOT NULL DEFAULT '', state TEXT NOT NULL DEFAULT '', zip TEXT NOT NULL DEFAULT '', phone TEXT NOT NULL DEFAULT '', date TEXT NOT NULL DEFAULT 'September 21, 2026' ); CREATE TABLE IF NOT EXISTS ba_subscription( owner TEXT PRIMARY KEY, status TEXT NOT NULL DEFAULT 'active', next_date TEXT NOT NULL DEFAULT 'September 21, 2026', address TEXT NOT NULL DEFAULT '125 Offline Review Lane, New York, NY 10001', skipped INTEGER NOT NULL DEFAULT 0, updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP ); """ ) connection.commit() return connection def auth_context(request: Request): current = request.cookies.get("__Host-blueapron-session") or request.cookies.get("blueapron_session") _, auth = open_site_services() token, session = auth.ensure_session(current) return auth, token, session, token != current def _claim_box(connection, token: str, account_id: str): """Adopt an anonymous/legacy box once; a saved account box wins on login.""" owner = "account:" + account_id tables = ("ba_plan", "ba_cart", "ba_addons", "ba_delivery") if connection.execute("SELECT 1 FROM ba_plan WHERE session=?", (owner,)).fetchone() is None: for table in tables: connection.execute(f"UPDATE {table} SET session=? WHERE session=?", (owner, token)) connection.execute("INSERT OR IGNORE INTO ba_plan(session) VALUES(?)", (owner,)) # Never leave an adopted guest box available through an old session. for table in tables: connection.execute(f"DELETE FROM {table} WHERE session=?", (token,)) return owner def box_rotation(token: str): # Ensure site tables exist before entering the auth store's transaction. connection = database() connection.close() def rotated(connection, old_digest: str, new_digest: str): previous = connection.execute("SELECT account_id FROM local_auth_sessions WHERE session_digest=?", (old_digest,)).fetchone() current = connection.execute("SELECT account_id FROM local_auth_sessions WHERE session_digest=?", (new_digest,)).fetchone() # Signing directly from A into B must never transfer A's legacy box to B. owner = previous["account_id"] if previous["account_id"] is not None else current["account_id"] _claim_box(connection, token, owner) return rotated def session_id(request: Request): _, token, session, new = auth_context(request) if session.get("authenticated"): with database() as connection: connection.execute("BEGIN IMMEDIATE") owner = _claim_box(connection, token, session["account"]["account_id"]) connection.commit() # The authenticated cookie already exists; the storage owner is never a cookie. return owner, False return token, new class InvalidJsonObject(ValueError): pass @app.exception_handler(InvalidJsonObject) async def invalid_json_object(_request: Request, exc: InvalidJsonObject): return JSONResponse({"error": str(exc)}, 422) async def request_object(request: Request): try: data = await request.json() except (ValueError, UnicodeDecodeError) as exc: raise InvalidJsonObject("Send a JSON object body.") from exc if not isinstance(data, dict): raise InvalidJsonObject("Send a JSON object body.") return data def set_cookie(response, request: Request, token: str): if request.url.scheme == "https": response.set_cookie("__Host-blueapron-session", token, secure=True, httponly=True, samesite="lax", path="/") else: response.set_cookie("blueapron_session", token, httponly=True, samesite="lax", path="/") def ensure_plan(connection, session): connection.execute("INSERT OR IGNORE INTO ba_plan(session) VALUES(?)", (session,)) connection.commit() return dict(connection.execute("SELECT * FROM ba_plan WHERE session=?", (session,)).fetchone()) def cart_payload(session): with database() as connection: plan = ensure_plan(connection, session) rows = [dict(row) for row in connection.execute("SELECT * FROM ba_cart WHERE session=? ORDER BY rowid", (session,))] addons = [dict(row) for row in connection.execute("SELECT * FROM ba_addons WHERE session=? ORDER BY rowid", (session,))] delivery_row = connection.execute("SELECT * FROM ba_delivery WHERE session=?", (session,)).fetchone() meal_price = 11.99 for row in rows: recipe = BY_ID.get(row["recipe_id"]) row.update(name=recipe["name"] if recipe else "Meal", image=recipe.get("image") if recipe else None) row["unit_price"] = meal_price + (3.99 if row["upgrade"] else 0) row["line_total"] = round(row["unit_price"] * plan["servings"] * row["qty"], 2) for row in addons: item = ADDONS[row["addon_id"]] row.update(name=item["name"], unit_price=item["price"], line_total=round(item["price"] * row["qty"], 2)) subtotal = round(sum(row["line_total"] for row in rows) + sum(row["line_total"] for row in addons), 2) discount = round(subtotal * 0.05, 2) if subtotal else 0 shipping = 9.99 if subtotal and subtotal < 100 else 0 tax = round((subtotal - discount + shipping) * 0.08875, 2) if subtotal else 0 return { "plan": plan, "items": rows, "addons": addons, "delivery": dict(delivery_row) if delivery_row else None, "selected_meals": sum(row["qty"] for row in rows), "minimum_met": sum(row["qty"] for row in rows) >= plan["meals"], "subtotal": subtotal, "discount": discount, "shipping": shipping, "tax": tax, "total": round(subtotal - discount + shipping + tax, 2), } @app.get("/healthz") def health(): return {"ok": True, "site_id": "blueapron"} @app.get("/__websitebench/health") def harbor_health(): return {"status": "ok"} @app.get("/static/recipes/{name}") def recipe_image(name: str): if not re.fullmatch(r"recipe-\d{4}\.webp", name): return JSONResponse({}, 404) path = ROOT / "static" / "recipes" / name return FileResponse(path) if path.is_file() else JSONResponse({}, 404) @app.get("/static/{name}") def static(name: str): if name not in {"style.css", "source.css", "app.js", "logo.svg", "home-hero.png", "menu-hero.webp", "gifts-hero.png", "vision-hero.png", "detail-ingredients.png", "menu-current-01.png", "menu-current-02.png", "menu-current-03.png", "menu-current-04.png", "menu-side-01.png", "menu-side-02.png", "menu-side-03.png", "menu-side-04.png"}: return JSONResponse({}, 404) path = ROOT / "static" / name return FileResponse(path) if path.is_file() else JSONResponse({}, 404) @app.get("/api/recipes") def recipes(q: str = "", category: str = "All", calories: int = 0, limit: int = 360): query = q.casefold().strip() result = RECIPES if query: result = [item for item in result if query in (item["name"] + " " + item["description"] + " " + " ".join(item["ingredients"])).casefold()] if category != "All": result = [item for item in result if item["category"] == category] if calories: result = [item for item in result if int(re.sub(r"\D", "", item.get("calories") or "99999") or 99999) <= calories] return {"count": len(result), "recipes": result[: max(1, min(limit, 360))]} @app.get("/api/recipes/{slug}") def recipe(slug: str): item = BY_SLUG.get(slug) return item if item else JSONResponse({"error": "Recipe not found"}, 404) @app.get("/api/cart") def get_cart(request: Request): session, new = session_id(request) response = JSONResponse(cart_payload(session)) if new: set_cookie(response, request, session) return response @app.put("/api/plan") async def update_plan(request: Request): session, new = session_id(request) data = await request_object(request) try: servings, meals = int(data.get("servings")), int(data.get("meals")) except (TypeError, ValueError): return JSONResponse({"error": "Choose servings and meals per week."}, 422) if servings not in {2, 4} or meals not in {2, 3, 4, 5}: return JSONResponse({"error": "That plan combination is not available."}, 422) preference = str(data.get("preference", "All")) with database() as connection: ensure_plan(connection, session) connection.execute("UPDATE ba_plan SET servings=?,meals=?,preference=? WHERE session=?", (servings, meals, preference, session)) connection.commit() response = JSONResponse(cart_payload(session)) if new: set_cookie(response, request, session) return response @app.post("/api/cart") async def add_cart(request: Request): session, new = session_id(request) data = await request_object(request) recipe_id = str(data.get("recipe_id", "")) if recipe_id not in BY_ID: return JSONResponse({"error": "Choose an available meal."}, 422) upgrade = str(data.get("upgrade", "")) if upgrade not in {"", "Premium protein"}: return JSONResponse({"error": "Unknown protein option."}, 422) with database() as connection: connection.execute("BEGIN IMMEDIATE") existing = connection.execute("SELECT qty,upgrade FROM ba_cart WHERE session=? AND recipe_id=?", (session, recipe_id)).fetchone() if existing and existing["upgrade"] != upgrade: return JSONResponse({"error": "Remove the existing meal before choosing a different protein option."}, 409) if existing and existing["qty"] >= 4: return JSONResponse({"error": "Maximum quantity is 4."}, 409) connection.execute( "INSERT INTO ba_cart(session,recipe_id,qty,upgrade) VALUES(?,?,1,?) ON CONFLICT(session,recipe_id) DO UPDATE SET qty=MIN(ba_cart.qty+1,4),upgrade=excluded.upgrade", (session, recipe_id, upgrade), ) connection.commit() response = JSONResponse(cart_payload(session)) if new: set_cookie(response, request, session) return response @app.patch("/api/cart/{recipe_id}") async def change_cart(recipe_id: str, request: Request): session, _ = session_id(request) data = await request_object(request) raw_qty = data.get("qty", 0) try: if isinstance(raw_qty, bool) or not isinstance(raw_qty, (int, str)): raise ValueError("not an integer") qty = max(0, min(int(raw_qty), 4)) except (TypeError, ValueError): return JSONResponse({"error": "Quantity must be an integer."}, 422) with database() as connection: if qty: connection.execute("UPDATE ba_cart SET qty=? WHERE session=? AND recipe_id=?", (qty, session, recipe_id)) else: connection.execute("DELETE FROM ba_cart WHERE session=? AND recipe_id=?", (session, recipe_id)) connection.commit() return cart_payload(session) @app.post("/api/addons") async def add_addon(request: Request): session, new = session_id(request) data = await request_object(request) addon_id = str(data.get("addon_id", "")) if addon_id not in ADDONS: return JSONResponse({"error": "Unknown add-on."}, 422) with database() as connection: connection.execute("BEGIN IMMEDIATE") existing = connection.execute("SELECT qty FROM ba_addons WHERE session=? AND addon_id=?", (session, addon_id)).fetchone() if existing and existing["qty"] >= 4: return JSONResponse({"error": "Maximum add-on quantity is 4."}, 409) connection.execute("INSERT INTO ba_addons(session,addon_id,qty) VALUES(?,?,1) ON CONFLICT(session,addon_id) DO UPDATE SET qty=MIN(ba_addons.qty+1,4)", (session, addon_id)) connection.commit() response = JSONResponse(cart_payload(session)) if new: set_cookie(response, request, session) return response @app.patch("/api/addons/{addon_id}") async def change_addon(addon_id: str, request: Request): session, _ = session_id(request) data = await request_object(request) quantity = data.get("qty") if addon_id not in ADDONS: return JSONResponse({"error": "Unknown add-on."}, 422) if type(quantity) is not int or not 0 <= quantity <= 4: return JSONResponse({"error": "Add-on quantity must be an integer from 0 to 4."}, 422) with database() as connection: if quantity: connection.execute("UPDATE ba_addons SET qty=? WHERE session=? AND addon_id=?", (quantity, session, addon_id)) else: connection.execute("DELETE FROM ba_addons WHERE session=? AND addon_id=?", (session, addon_id)) connection.commit() return cart_payload(session) @app.put("/api/delivery") async def delivery(request: Request): session, new = session_id(request) data = await request_object(request) required = ["name", "address", "city", "state", "zip", "phone"] missing = [key for key in required if not str(data.get(key, "")).strip()] if missing: return JSONResponse({"error": "Complete all required delivery fields.", "fields": missing}, 422) zip_code = str(data["zip"]).strip() if not re.fullmatch(r"\d{5}", zip_code) or zip_code.startswith(("000", "999")): return JSONResponse({"error": "We don't currently deliver to this ZIP code.", "fields": ["zip"]}, 422) with database() as connection: connection.execute( "INSERT INTO ba_delivery(session,name,address,city,state,zip,phone,date) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(session) DO UPDATE SET name=excluded.name,address=excluded.address,city=excluded.city,state=excluded.state,zip=excluded.zip,phone=excluded.phone,date=excluded.date", (session, *(str(data.get(key, "")).strip() for key in required), str(data.get("date", "September 21, 2026"))), ) connection.commit() response = JSONResponse(cart_payload(session)) if new: set_cookie(response, request, session) return response @app.post("/api/checkout/review") def checkout_review(request: Request): session, _ = session_id(request) payload = cart_payload(session) if not payload["minimum_met"]: return JSONResponse({"error": f"Select at least {payload['plan']['meals']} meals for this plan."}, 422) if not payload["delivery"]: return JSONResponse({"error": "Add a delivery address before continuing."}, 422) return {**payload, "payment_adapter": "local-sandbox", "purchase_submitted": False} @app.get("/api/auth/session") def auth_session(request: Request): _, token, session, new = auth_context(request) response = JSONResponse(session) if new: set_cookie(response, request, token) return response @app.post("/api/auth/register/start") async def register_start(request: Request): auth, token, _, new = auth_context(request) data = await request_object(request) display_name = (str(data.get("first_name", "")) + " " + str(data.get("last_name", ""))).strip() try: result = auth.start_registration(token, email=str(data.get("email", "")), display_name=display_name, password=str(data.get("password", "")), restart_invalid_flow=True) mail = auth.local_mail_for_session(token, purpose="registration") except AuthError as exc: return JSONResponse({"error": str(exc)}, 422) response = JSONResponse({**result, "verification_code": mail.get("verification_code") if mail else None, "delivery": "local-sandbox"}) if new: set_cookie(response, request, token) return response @app.post("/api/auth/register/verify") async def register_verify(request: Request): auth, token, _, _ = auth_context(request) data = await request_object(request) try: auth.verify_registration_code(token, str(data.get("code", ""))) result = auth.complete_registration(token, session_rotation_callback=box_rotation(token)) except AuthError as exc: return JSONResponse({"error": str(exc)}, 422) response = JSONResponse({"authenticated": True, "account": result["account"]}) set_cookie(response, request, result["session_token"]) return response @app.post("/api/auth/signin") async def signin(request: Request): auth, token, _, _ = auth_context(request) data = await request_object(request) try: result = auth.sign_in(token, email=str(data.get("email", "")), password=str(data.get("password", "")), session_rotation_callback=box_rotation(token)) except AuthError as exc: return JSONResponse({"error": str(exc)}, 401) response = JSONResponse({"authenticated": True, "account": result["account"]}) set_cookie(response, request, result["session_token"]) return response @app.post("/api/auth/signout") def signout(request: Request): auth, token, _, _ = auth_context(request) auth.sign_out(token) response = JSONResponse({"authenticated": False, "account": None}) response.delete_cookie("blueapron_session", path="/") response.delete_cookie("__Host-blueapron-session", path="/", secure=True) return response def authenticated_owner(request: Request): _, _, session, _ = auth_context(request) if not session.get("authenticated"): return None account = session.get("account") or {} return account.get("email_normalized") or account.get("email") @app.get("/api/subscription") def subscription(request: Request): owner = authenticated_owner(request) if not owner: return JSONResponse({"error": "Sign in to manage your deliveries."}, 401) with database() as connection: connection.execute("INSERT OR IGNORE INTO ba_subscription(owner) VALUES(?)", (owner,)) connection.commit() return dict(connection.execute("SELECT * FROM ba_subscription WHERE owner=?", (owner,)).fetchone()) @app.patch("/api/subscription") async def update_subscription(request: Request): owner = authenticated_owner(request) if not owner: return JSONResponse({"error": "Sign in to manage your deliveries."}, 401) data = await request_object(request) action = str(data.get("action", "")) with database() as connection: connection.execute("INSERT OR IGNORE INTO ba_subscription(owner) VALUES(?)", (owner,)) if action == "skip": connection.execute("UPDATE ba_subscription SET skipped=1,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (owner,)) elif action in {"pause", "cancel", "resume"}: status = {"pause": "paused", "cancel": "cancelled", "resume": "active"}[action] connection.execute("UPDATE ba_subscription SET status=?,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (status, owner)) elif action == "address" and str(data.get("address", "")).strip(): connection.execute("UPDATE ba_subscription SET address=?,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (str(data["address"]).strip(), owner)) elif action == "date" and str(data.get("date", "")).strip(): connection.execute("UPDATE ba_subscription SET next_date=?,updated_at=CURRENT_TIMESTAMP WHERE owner=?", (str(data["date"]).strip(), owner)) else: return JSONResponse({"error": "Choose a valid subscription action."}, 422) connection.commit() return dict(connection.execute("SELECT * FROM ba_subscription WHERE owner=?", (owner,)).fetchone()) @app.post("/api/reset-request") async def reset_request(request: Request): data = await request_object(request) if not re.fullmatch(r"[^@\s]+@[^@\s]+\.[^@\s]+", str(data.get("email", ""))): return JSONResponse({"error": "Enter a valid email address."}, 422) return {"accepted": False, "delivery": "disabled", "message": "Offline review: no reset email was sent."} INDEX = """Blue Apron | Meal Kits, Oven-Ready & Ready-to-Eat Meals - No Subscription
""" @app.get("/{path:path}", response_class=HTMLResponse) def frontend(path: str): return INDEX